blob: edb71e84a312e202f2c8153096880b344161b97e [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000026#include "clang/Lex/ModuleLoader.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Sema/DeclSpec.h"
28#include "clang/Sema/ExternalSemaSource.h"
29#include "clang/Sema/Overload.h"
30#include "clang/Sema/Scope.h"
31#include "clang/Sema/ScopeInfo.h"
32#include "clang/Sema/Sema.h"
33#include "clang/Sema/SemaInternal.h"
34#include "clang/Sema/TemplateDeduction.h"
35#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000036#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000038#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000039#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000040#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000041#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000042#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000043#include <algorithm>
44#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000045#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000046#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000047#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000048#include <set>
49#include <utility>
50#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000051
52using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000053using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000054
John McCallf6c8a4e2009-11-10 07:01:13 +000055namespace {
56 class UnqualUsingEntry {
57 const DeclContext *Nominated;
58 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000059
John McCallf6c8a4e2009-11-10 07:01:13 +000060 public:
61 UnqualUsingEntry(const DeclContext *Nominated,
62 const DeclContext *CommonAncestor)
63 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
64 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000065
John McCallf6c8a4e2009-11-10 07:01:13 +000066 const DeclContext *getCommonAncestor() const {
67 return CommonAncestor;
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-11-10 07:01:13 +000070 const DeclContext *getNominatedNamespace() const {
71 return Nominated;
72 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 // Sort by the pointer value of the common ancestor.
75 struct Comparator {
76 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
77 return L.getCommonAncestor() < R.getCommonAncestor();
78 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000079
John McCallf6c8a4e2009-11-10 07:01:13 +000080 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
81 return E.getCommonAncestor() < DC;
82 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
85 return DC < E.getCommonAncestor();
86 }
87 };
88 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000089
John McCallf6c8a4e2009-11-10 07:01:13 +000090 /// A collection of using directives, as used by C++ unqualified
91 /// lookup.
92 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000093 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
John McCallf6c8a4e2009-11-10 07:01:13 +000095 ListTy list;
96 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000097
John McCallf6c8a4e2009-11-10 07:01:13 +000098 public:
99 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000100
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 // During unqualified name lookup, the names appear as if they
104 // were declared in the nearest enclosing namespace which contains
105 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000106 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000108
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000113 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000117 for (auto *I : S->using_directives())
118 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000119 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000120 }
121 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000122
123 // Visits a context and collect all of its using directives
124 // recursively. Treats all using directives as if they were
125 // declared in the context.
126 //
127 // A given context is only every visited once, so it is important
128 // that contexts be visited from the inside out in order to get
129 // the effective DCs right.
130 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
131 if (!visited.insert(DC))
132 return;
133
134 addUsingDirectives(DC, EffectiveDC);
135 }
136
137 // Visits a using directive and collects all of its using
138 // directives recursively. Treats all using directives as if they
139 // were declared in the effective DC.
140 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
141 DeclContext *NS = UD->getNominatedNamespace();
142 if (!visited.insert(NS))
143 return;
144
145 addUsingDirective(UD, EffectiveDC);
146 addUsingDirectives(NS, EffectiveDC);
147 }
148
149 // Adds all the using directives in a context (and those nominated
150 // by its using directives, transitively) as if they appeared in
151 // the given effective context.
152 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000154 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000155 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000156 DeclContext *NS = UD->getNominatedNamespace();
157 if (visited.insert(NS)) {
158 addUsingDirective(UD, EffectiveDC);
159 queue.push_back(NS);
160 }
161 }
162
163 if (queue.empty())
164 return;
165
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000166 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000167 }
168 }
169
170 // Add a using directive as if it had been declared in the given
171 // context. This helps implement C++ [namespace.udir]p3:
172 // The using-directive is transitive: if a scope contains a
173 // using-directive that nominates a second namespace that itself
174 // contains using-directives, the effect is as if the
175 // using-directives from the second namespace also appeared in
176 // the first.
177 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
178 // Find the common ancestor between the effective context and
179 // the nominated namespace.
180 DeclContext *Common = UD->getNominatedNamespace();
181 while (!Common->Encloses(EffectiveDC))
182 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000183 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184
John McCallf6c8a4e2009-11-10 07:01:13 +0000185 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
186 }
187
188 void done() {
189 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
190 }
191
John McCallf6c8a4e2009-11-10 07:01:13 +0000192 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193
John McCallf6c8a4e2009-11-10 07:01:13 +0000194 const_iterator begin() const { return list.begin(); }
195 const_iterator end() const { return list.end(); }
196
197 std::pair<const_iterator,const_iterator>
198 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000199 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000200 UnqualUsingEntry::Comparator());
201 }
202 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000203}
204
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205// Retrieve the set of identifier namespaces that correspond to a
206// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000207static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
208 bool CPlusPlus,
209 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 unsigned IDNS = 0;
211 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000212 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000213 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000214 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000215 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000217 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000219 if (Redeclaration)
220 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000221 }
Richard Smith541b38b2013-09-20 01:15:31 +0000222 if (Redeclaration)
223 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000224 break;
225
John McCallb9467b62010-04-24 01:30:58 +0000226 case Sema::LookupOperatorName:
227 // Operator lookup is its own crazy thing; it is not the same
228 // as (e.g.) looking up an operator name for redeclaration.
229 assert(!Redeclaration && "cannot do redeclaration operator lookup");
230 IDNS = Decl::IDNS_NonMemberOperator;
231 break;
232
Douglas Gregor889ceb72009-02-03 19:21:40 +0000233 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000234 if (CPlusPlus) {
235 IDNS = Decl::IDNS_Type;
236
237 // When looking for a redeclaration of a tag name, we add:
238 // 1) TagFriend to find undeclared friend decls
239 // 2) Namespace because they can't "overload" with tag decls.
240 // 3) Tag because it includes class templates, which can't
241 // "overload" with tag decls.
242 if (Redeclaration)
243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
244 } else {
245 IDNS = Decl::IDNS_Tag;
246 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000247 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000248
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000249 case Sema::LookupLabel:
250 IDNS = Decl::IDNS_Label;
251 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000252
Douglas Gregor889ceb72009-02-03 19:21:40 +0000253 case Sema::LookupMemberName:
254 IDNS = Decl::IDNS_Member;
255 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000256 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 break;
258
259 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000260 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
261 break;
262
Douglas Gregor889ceb72009-02-03 19:21:40 +0000263 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000264 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000265 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000266
John McCall84d87672009-12-10 09:41:52 +0000267 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000268 assert(Redeclaration && "should only be used for redecl lookup");
269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
270 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
271 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000272 break;
273
Douglas Gregor79947a22009-04-24 00:11:27 +0000274 case Sema::LookupObjCProtocolName:
275 IDNS = Decl::IDNS_ObjCProtocol;
276 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277
Douglas Gregor39982192010-08-15 06:18:01 +0000278 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000280 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
281 | Decl::IDNS_Type;
282 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000283 }
284 return IDNS;
285}
286
John McCallea305ed2009-12-18 10:40:03 +0000287void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000288 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000289 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000290
Richard Smithbdd14642014-02-04 01:14:30 +0000291 // If we're looking for one of the allocation or deallocation
292 // operators, make sure that the implicitly-declared new and delete
293 // operators can be found.
294 switch (NameInfo.getName().getCXXOverloadedOperator()) {
295 case OO_New:
296 case OO_Delete:
297 case OO_Array_New:
298 case OO_Array_Delete:
299 SemaRef.DeclareGlobalNewDelete();
300 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000301
Richard Smithbdd14642014-02-04 01:14:30 +0000302 default:
303 break;
304 }
Douglas Gregor15197662013-04-03 23:06:26 +0000305
Richard Smithbdd14642014-02-04 01:14:30 +0000306 // Compiler builtins are always visible, regardless of where they end
307 // up being declared.
308 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
309 if (unsigned BuiltinID = Id->getBuiltinID()) {
310 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
311 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000312 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000313 }
John McCallea305ed2009-12-18 10:40:03 +0000314}
315
Alp Tokerc1086762013-12-07 13:51:35 +0000316bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000317 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000318 assert(ResultKind != NotFound || Decls.size() == 0);
319 assert(ResultKind != Found || Decls.size() == 1);
320 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
321 (Decls.size() == 1 &&
322 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
323 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
324 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000325 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
326 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000327 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
328 (Ambiguity == AmbiguousBaseSubobjectTypes ||
329 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000330 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000331}
John McCall19c1bfd2010-08-25 05:32:35 +0000332
John McCall9f3059a2009-10-09 21:13:30 +0000333// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000334void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000335 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000336}
337
Richard Smith3876cc82013-10-30 01:02:04 +0000338/// Get a representative context for a declaration such that two declarations
339/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000340static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000341 // For function-local declarations, use that function as the context. This
342 // doesn't account for scopes within the function; the caller must deal with
343 // those.
344 DeclContext *DC = D->getLexicalDeclContext();
345 if (DC->isFunctionOrMethod())
346 return DC;
347
348 // Otherwise, look at the semantic context of the declaration. The
349 // declaration must have been found there.
350 return D->getDeclContext()->getRedeclContext();
351}
352
John McCall283b9012009-11-22 00:44:51 +0000353/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000354void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000355 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000356
John McCall9f3059a2009-10-09 21:13:30 +0000357 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000358 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000359 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000360 return;
361 }
362
John McCall283b9012009-11-22 00:44:51 +0000363 // If there's a single decl, we need to examine it to decide what
364 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000365 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000366 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
367 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000368 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000369 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000370 ResultKind = FoundUnresolvedValue;
371 return;
372 }
John McCall9f3059a2009-10-09 21:13:30 +0000373
John McCall6538c932009-10-10 05:48:19 +0000374 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000375 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000376
John McCall9f3059a2009-10-09 21:13:30 +0000377 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000378 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379
John McCall9f3059a2009-10-09 21:13:30 +0000380 bool Ambiguous = false;
381 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000382 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000383
384 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385
John McCall9f3059a2009-10-09 21:13:30 +0000386 unsigned I = 0;
387 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000388 NamedDecl *D = Decls[I]->getUnderlyingDecl();
389 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000390
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000391 // Ignore an invalid declaration unless it's the only one left.
392 if (D->isInvalidDecl() && I < N-1) {
393 Decls[I] = Decls[--N];
394 continue;
395 }
396
Douglas Gregor13e65872010-08-11 14:45:53 +0000397 // Redeclarations of types via typedef can occur both within a scope
398 // and, through using declarations and directives, across scopes. There is
399 // no ambiguity if they all refer to the same type, so unique based on the
400 // canonical type.
401 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
402 if (!TD->getDeclContext()->isRecord()) {
403 QualType T = SemaRef.Context.getTypeDeclType(TD);
404 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
405 // The type is not unique; pull something off the back and continue
406 // at this index.
407 Decls[I] = Decls[--N];
408 continue;
409 }
410 }
411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000412
John McCallf0f1cf02009-11-17 07:50:12 +0000413 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000414 // If it's not unique, pull something off the back (and
415 // continue at this index).
416 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000417 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418 }
419
Douglas Gregor13e65872010-08-11 14:45:53 +0000420 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000421
Douglas Gregor13e65872010-08-11 14:45:53 +0000422 if (isa<UnresolvedUsingValueDecl>(D)) {
423 HasUnresolved = true;
424 } else if (isa<TagDecl>(D)) {
425 if (HasTag)
426 Ambiguous = true;
427 UniqueTagIndex = I;
428 HasTag = true;
429 } else if (isa<FunctionTemplateDecl>(D)) {
430 HasFunction = true;
431 HasFunctionTemplate = true;
432 } else if (isa<FunctionDecl>(D)) {
433 HasFunction = true;
434 } else {
435 if (HasNonFunction)
436 Ambiguous = true;
437 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000438 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000439 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000440 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000441
John McCall9f3059a2009-10-09 21:13:30 +0000442 // C++ [basic.scope.hiding]p2:
443 // A class name or enumeration name can be hidden by the name of
444 // an object, function, or enumerator declared in the same
445 // scope. If a class or enumeration name and an object, function,
446 // or enumerator are declared in the same scope (in any order)
447 // with the same name, the class or enumeration name is hidden
448 // wherever the object, function, or enumerator name is visible.
449 // But it's still an error if there are distinct tag types found,
450 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000451 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000452 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000453 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
454 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000455 Decls[UniqueTagIndex] = Decls[--N];
456 else
457 Ambiguous = true;
458 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000459
John McCall9f3059a2009-10-09 21:13:30 +0000460 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000461
John McCall80053822009-12-03 00:58:24 +0000462 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000463 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000464
John McCall9f3059a2009-10-09 21:13:30 +0000465 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000466 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000467 else if (HasUnresolved)
468 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000469 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000470 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000471 else
John McCall27b18f82009-11-17 02:14:36 +0000472 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000473}
474
John McCall5cebab12009-11-18 07:57:50 +0000475void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000476 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000477 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000478 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
479 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000480 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000481}
482
John McCall5cebab12009-11-18 07:57:50 +0000483void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000484 Paths = new CXXBasePaths;
485 Paths->swap(P);
486 addDeclsFromBasePaths(*Paths);
487 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000488 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000489}
490
John McCall5cebab12009-11-18 07:57:50 +0000491void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000492 Paths = new CXXBasePaths;
493 Paths->swap(P);
494 addDeclsFromBasePaths(*Paths);
495 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000496 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000497}
498
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000499void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000500 Out << Decls.size() << " result(s)";
501 if (isAmbiguous()) Out << ", ambiguous";
502 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
John McCall9f3059a2009-10-09 21:13:30 +0000504 for (iterator I = begin(), E = end(); I != E; ++I) {
505 Out << "\n";
506 (*I)->print(Out, 2);
507 }
508}
509
Douglas Gregord3a59182010-02-12 05:48:04 +0000510/// \brief Lookup a builtin function, when name lookup would otherwise
511/// fail.
512static bool LookupBuiltin(Sema &S, LookupResult &R) {
513 Sema::LookupNameKind NameKind = R.getLookupKind();
514
515 // If we didn't find a use of this identifier, and if the identifier
516 // corresponds to a compiler builtin, create the decl object for the builtin
517 // now, injecting it into translation unit scope, and return it.
518 if (NameKind == Sema::LookupOrdinaryName ||
519 NameKind == Sema::LookupRedeclarationWithLinkage) {
520 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
521 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000522 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
523 II == S.getFloat128Identifier()) {
524 // libstdc++4.7's type_traits expects type __float128 to exist, so
525 // insert a dummy type to make that header build in gnu++11 mode.
526 R.addDecl(S.getASTContext().getFloat128StubType());
527 return true;
528 }
529
Douglas Gregord3a59182010-02-12 05:48:04 +0000530 // If this is a builtin on this (or all) targets, create the decl.
531 if (unsigned BuiltinID = II->getBuiltinID()) {
532 // In C++, we don't have any predefined library functions like
533 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000534 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000535 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
536 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000537
538 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
539 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000540 R.isForRedeclaration(),
541 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000542 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000543 return true;
544 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000545 }
546 }
547 }
548
549 return false;
550}
551
Douglas Gregor7454c562010-07-02 20:37:36 +0000552/// \brief Determine whether we can declare a special member function within
553/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000554static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000555 // We need to have a definition for the class.
556 if (!Class->getDefinition() || Class->isDependentContext())
557 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor7454c562010-07-02 20:37:36 +0000559 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000560 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000561}
562
563void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000564 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000565 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000566
567 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000568 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000569 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
Douglas Gregora6d69502010-07-02 23:41:54 +0000571 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000572 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000573 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000575 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000576 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000577 DeclareImplicitCopyAssignment(Class);
578
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000579 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000580 // If the move constructor has not yet been declared, do so now.
581 if (Class->needsImplicitMoveConstructor())
582 DeclareImplicitMoveConstructor(Class); // might not actually do it
583
584 // If the move assignment operator has not yet been declared, do so now.
585 if (Class->needsImplicitMoveAssignment())
586 DeclareImplicitMoveAssignment(Class); // might not actually do it
587 }
588
Douglas Gregor7454c562010-07-02 20:37:36 +0000589 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000590 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000592}
593
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000595/// special member function.
596static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
597 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000598 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000599 case DeclarationName::CXXDestructorName:
600 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000602 case DeclarationName::CXXOperatorName:
603 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000605 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000609 return false;
610}
611
612/// \brief If there are any implicit member functions with the given name
613/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000615 DeclarationName Name,
616 const DeclContext *DC) {
617 if (!DC)
618 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000620 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000621 case DeclarationName::CXXConstructorName:
622 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000623 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000624 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000625 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000626 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000627 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000628 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000629 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000630 Record->needsImplicitMoveConstructor())
631 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000632 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000633 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000635 case DeclarationName::CXXDestructorName:
636 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000637 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000638 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000639 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000640 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000642 case DeclarationName::CXXOperatorName:
643 if (Name.getCXXOverloadedOperator() != OO_Equal)
644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
Sebastian Redl22653ba2011-08-30 19:58:05 +0000646 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000647 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000648 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000649 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000650 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000651 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000652 Record->needsImplicitMoveAssignment())
653 S.DeclareImplicitMoveAssignment(Class);
654 }
655 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000656 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000657
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000658 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000660 }
661}
Douglas Gregor7454c562010-07-02 20:37:36 +0000662
John McCall9f3059a2009-10-09 21:13:30 +0000663// Adds all qualifying matches for a name within a decl context to the
664// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000665static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000666 bool Found = false;
667
Douglas Gregor7454c562010-07-02 20:37:36 +0000668 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000669 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000670 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Douglas Gregor7454c562010-07-02 20:37:36 +0000672 // Perform lookup into this declaration context.
David Blaikieff7d47a2012-12-19 00:45:41 +0000673 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
674 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
675 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000676 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000677 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000678 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000679 Found = true;
680 }
681 }
John McCall9f3059a2009-10-09 21:13:30 +0000682
Douglas Gregord3a59182010-02-12 05:48:04 +0000683 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
684 return true;
685
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000686 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000687 != DeclarationName::CXXConversionFunctionName ||
688 R.getLookupName().getCXXNameType()->isDependentType() ||
689 !isa<CXXRecordDecl>(DC))
690 return Found;
691
692 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000694 // name lookup. Instead, any conversion function templates visible in the
695 // context of the use are considered. [...]
696 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000697 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000698 return Found;
699
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000700 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
701 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000702 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
703 if (!ConvTemplate)
704 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000705
Chandler Carruth3a693b72010-01-31 11:44:02 +0000706 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707 // add the conversion function template. When we deduce template
708 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709 // type of the new declaration with the type of the function template.
710 if (R.isForRedeclaration()) {
711 R.addDecl(ConvTemplate);
712 Found = true;
713 continue;
714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000716 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717 // [...] For each such operator, if argument deduction succeeds
718 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000719 // name lookup.
720 //
721 // When referencing a conversion function for any purpose other than
722 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000724 // specialization into the result set. We do this to avoid forcing all
725 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000726 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000727 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
729 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000730 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
731 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000732
Chandler Carruth3a693b72010-01-31 11:44:02 +0000733 // Compute the type of the function that we would expect the conversion
734 // function to have, if it were to match the name given.
735 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000736 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000737 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000738 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000739 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000740 QualType ExpectedType
741 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000742 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000743
Chandler Carruth3a693b72010-01-31 11:44:02 +0000744 // Perform template argument deduction against the type that we would
745 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000746 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000747 Specialization, Info)
748 == Sema::TDK_Success) {
749 R.addDecl(Specialization);
750 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000751 }
752 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000753
John McCall9f3059a2009-10-09 21:13:30 +0000754 return Found;
755}
756
John McCallf6c8a4e2009-11-10 07:01:13 +0000757// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000758static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000760 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000761
762 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
763
John McCallf6c8a4e2009-11-10 07:01:13 +0000764 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000765 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000766
John McCallf6c8a4e2009-11-10 07:01:13 +0000767 // Perform direct name lookup into the namespaces nominated by the
768 // using directives whose common ancestor is this namespace.
769 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000770 std::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000771
John McCallf6c8a4e2009-11-10 07:01:13 +0000772 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000773 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000774 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000775
776 R.resolveKind();
777
778 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000779}
780
781static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000782 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000783 return Ctx->isFileContext();
784 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000785}
Douglas Gregored8f2882009-01-30 01:04:22 +0000786
Douglas Gregor66230062010-03-15 14:33:29 +0000787// Find the next outer declaration context from this scope. This
788// routine actually returns the semantic outer context, which may
789// differ from the lexical context (encoded directly in the Scope
790// stack) when we are parsing a member of a class template. In this
791// case, the second element of the pair will be true, to indicate that
792// name lookup should continue searching in this semantic context when
793// it leaves the current template parameter scope.
794static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000795 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000796 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000798 OuterS = OuterS->getParent()) {
799 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000800 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000801 break;
802 }
803 }
804
805 // C++ [temp.local]p8:
806 // In the definition of a member of a class template that appears
807 // outside of the namespace containing the class template
808 // definition, the name of a template-parameter hides the name of
809 // a member of this namespace.
810 //
811 // Example:
812 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813 // namespace N {
814 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000815 //
816 // template<class T> class B {
817 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000819 // }
820 //
821 // template<class C> void N::B<C>::f(C) {
822 // C b; // C is the template parameter, not N::C
823 // }
824 //
825 // In this example, the lexical context we return is the
826 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000828 !S->getParent()->isTemplateParamScope())
829 return std::make_pair(Lexical, false);
830
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000832 // For the example, this is the scope for the template parameters of
833 // template<class C>.
834 Scope *OutermostTemplateScope = S->getParent();
835 while (OutermostTemplateScope->getParent() &&
836 OutermostTemplateScope->getParent()->isTemplateParamScope())
837 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000838
Douglas Gregor66230062010-03-15 14:33:29 +0000839 // Find the namespace context in which the original scope occurs. In
840 // the example, this is namespace N.
841 DeclContext *Semantic = DC;
842 while (!Semantic->isFileContext())
843 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Douglas Gregor66230062010-03-15 14:33:29 +0000845 // Find the declaration context just outside of the template
846 // parameter scope. This is the context in which the template is
847 // being lexically declaration (a namespace context). In the
848 // example, this is the global scope.
849 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
850 Lexical->Encloses(Semantic))
851 return std::make_pair(Semantic, true);
852
853 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000854}
855
Richard Smith541b38b2013-09-20 01:15:31 +0000856namespace {
857/// An RAII object to specify that we want to find block scope extern
858/// declarations.
859struct FindLocalExternScope {
860 FindLocalExternScope(LookupResult &R)
861 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
862 Decl::IDNS_LocalExtern) {
863 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
864 }
865 void restore() {
866 R.setFindLocalExtern(OldFindLocalExtern);
867 }
868 ~FindLocalExternScope() {
869 restore();
870 }
871 LookupResult &R;
872 bool OldFindLocalExtern;
873};
874}
875
John McCall27b18f82009-11-17 02:14:36 +0000876bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000877 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000878
879 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000880 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000881
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000882 // If this is the name of an implicitly-declared special member function,
883 // go through the scope stack to implicitly declare
884 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
885 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000886 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000887 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000890 // Implicitly declare member functions with the name we're looking for, if in
891 // fact we are in a scope where it matters.
892
Douglas Gregor889ceb72009-02-03 19:21:40 +0000893 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000894 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000895 I = IdResolver.begin(Name),
896 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000897
Douglas Gregor889ceb72009-02-03 19:21:40 +0000898 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000899 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000900 // ...During unqualified name lookup (3.4.1), the names appear as if
901 // they were declared in the nearest enclosing namespace which contains
902 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000903 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000904 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000905 //
906 // For example:
907 // namespace A { int i; }
908 // void foo() {
909 // int i;
910 // {
911 // using namespace A;
912 // ++i; // finds local 'i', A::i appears at global scope
913 // }
914 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000915 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000916 UnqualUsingDirectiveSet UDirs;
917 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000918 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000919 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +0000920
921 // When performing a scope lookup, we want to find local extern decls.
922 FindLocalExternScope FindLocals(R);
923
Douglas Gregor700792c2009-02-05 19:25:20 +0000924 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000925 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000926
Douglas Gregor889ceb72009-02-03 19:21:40 +0000927 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000928 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000929 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000930 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000931 if (NameKind == LookupRedeclarationWithLinkage) {
932 // Determine whether this (or a previous) declaration is
933 // out-of-scope.
934 if (!LeftStartingScope && !Initial->isDeclScope(*I))
935 LeftStartingScope = true;
936
937 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000938 // does not have linkage, skip it. If it's a template parameter,
939 // we still find it, so we can diagnose the invalid redeclaration.
940 if (LeftStartingScope && !((*I)->hasLinkage()) &&
941 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000942 R.setShadowed();
943 continue;
944 }
945 }
946
John McCall9f3059a2009-10-09 21:13:30 +0000947 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000948 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000949 }
950 }
John McCall9f3059a2009-10-09 21:13:30 +0000951 if (Found) {
952 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000953 if (S->isClassScope())
954 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
955 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000956 return true;
957 }
958
Richard Smith1c34fb72013-08-13 18:18:50 +0000959 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000960 // C++11 [class.friend]p11:
961 // If a friend declaration appears in a local class and the name
962 // specified is an unqualified name, a prior declaration is
963 // looked up without considering scopes that are outside the
964 // innermost enclosing non-class scope.
965 return false;
966 }
967
Douglas Gregor66230062010-03-15 14:33:29 +0000968 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
969 S->getParent() && !S->getParent()->isTemplateParamScope()) {
970 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000971 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000972 // lexical and semantic declaration contexts returned by
973 // findOuterContext(). This implements the name lookup behavior
974 // of C++ [temp.local]p8.
975 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +0000976 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +0000977 }
978
979 if (Ctx) {
980 DeclContext *OuterCtx;
981 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000982 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000983 if (SearchAfterTemplateScope)
984 OutsideOfTemplateParamDC = OuterCtx;
985
Douglas Gregorea166062010-03-15 15:26:48 +0000986 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000987 // We do not directly look into transparent contexts, since
988 // those entities will be found in the nearest enclosing
989 // non-transparent context.
990 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000991 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000992
993 // We do not look directly into function or method contexts,
994 // since all of the local variables and parameters of the
995 // function/method are present within the Scope.
996 if (Ctx->isFunctionOrMethod()) {
997 // If we have an Objective-C instance method, look for ivars
998 // in the corresponding interface.
999 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1000 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1001 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1002 ObjCInterfaceDecl *ClassDeclared;
1003 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001004 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001005 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001006 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1007 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001008 R.resolveKind();
1009 return true;
1010 }
1011 }
1012 }
1013 }
1014
1015 continue;
1016 }
1017
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001018 // If this is a file context, we need to perform unqualified name
1019 // lookup considering using directives.
1020 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001021 // If we haven't handled using directives yet, do so now.
1022 if (!VisitedUsingDirectives) {
1023 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001024 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1025 if (UCtx->isTransparentContext())
1026 continue;
1027
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001028 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001029 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001030
1031 // Find the innermost file scope, so we can add using directives
1032 // from local scopes.
1033 Scope *InnermostFileScope = S;
1034 while (InnermostFileScope &&
1035 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1036 InnermostFileScope = InnermostFileScope->getParent();
1037 UDirs.visitScopeChain(Initial, InnermostFileScope);
1038
1039 UDirs.done();
1040
1041 VisitedUsingDirectives = true;
1042 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001043
1044 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1045 R.resolveKind();
1046 return true;
1047 }
1048
1049 continue;
1050 }
1051
Douglas Gregor7f737c02009-09-10 16:57:35 +00001052 // Perform qualified name lookup into this context.
1053 // FIXME: In some cases, we know that every name that could be found by
1054 // this qualified name lookup will also be on the identifier chain. For
1055 // example, inside a class without any base classes, we never need to
1056 // perform qualified lookup because all of the members are on top of the
1057 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001058 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001059 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001060 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001061 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001062 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001063
John McCallf6c8a4e2009-11-10 07:01:13 +00001064 // Stop if we ran out of scopes.
1065 // FIXME: This really, really shouldn't be happening.
1066 if (!S) return false;
1067
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001068 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001069 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001070 return false;
1071
Douglas Gregor700792c2009-02-05 19:25:20 +00001072 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001073 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001074 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001075 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1076 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001077 if (!VisitedUsingDirectives) {
1078 UDirs.visitScopeChain(Initial, S);
1079 UDirs.done();
1080 }
Richard Smith541b38b2013-09-20 01:15:31 +00001081
1082 // If we're not performing redeclaration lookup, do not look for local
1083 // extern declarations outside of a function scope.
1084 if (!R.isForRedeclaration())
1085 FindLocals.restore();
1086
Douglas Gregor700792c2009-02-05 19:25:20 +00001087 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001088 // Unqualified name lookup in C++ requires looking into scopes
1089 // that aren't strictly lexical, and therefore we walk through the
1090 // context as well as walking through the scopes.
1091 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001092 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001093 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001094 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001095 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001096 // We found something. Look for anything else in our scope
1097 // with this same name and in an acceptable identifier
1098 // namespace, so that we can construct an overload set if we
1099 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001100 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001101 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001102 }
1103 }
1104
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001105 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001106 R.resolveKind();
1107 return true;
1108 }
1109
Ted Kremenekc37877d2013-10-08 17:08:03 +00001110 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001111 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1112 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1113 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001114 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001115 // lexical and semantic declaration contexts returned by
1116 // findOuterContext(). This implements the name lookup behavior
1117 // of C++ [temp.local]p8.
1118 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001119 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001121
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001122 if (Ctx) {
1123 DeclContext *OuterCtx;
1124 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001125 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001126 if (SearchAfterTemplateScope)
1127 OutsideOfTemplateParamDC = OuterCtx;
1128
1129 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1130 // We do not directly look into transparent contexts, since
1131 // those entities will be found in the nearest enclosing
1132 // non-transparent context.
1133 if (Ctx->isTransparentContext())
1134 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001135
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001136 // If we have a context, and it's not a context stashed in the
1137 // template parameter scope for an out-of-line definition, also
1138 // look into that context.
1139 if (!(Found && S && S->isTemplateParamScope())) {
1140 assert(Ctx->isFileContext() &&
1141 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001142
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001143 // Look into context considering using-directives.
1144 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1145 Found = true;
1146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001147
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001148 if (Found) {
1149 R.resolveKind();
1150 return true;
1151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001152
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001153 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1154 return false;
1155 }
1156 }
1157
Douglas Gregor3ce74932010-02-05 07:07:10 +00001158 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001159 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001160 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001161
John McCall9f3059a2009-10-09 21:13:30 +00001162 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001163}
1164
Richard Smith0e5d7b82013-07-25 23:08:39 +00001165/// \brief Find the declaration that a class temploid member specialization was
1166/// instantiated from, or the member itself if it is an explicit specialization.
1167static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1168 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1169}
1170
1171/// \brief Find the module in which the given declaration was defined.
1172static Module *getDefiningModule(Decl *Entity) {
1173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1174 // If this function was instantiated from a template, the defining module is
1175 // the module containing the pattern.
1176 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1177 Entity = Pattern;
1178 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1179 // If it's a class template specialization, find the template or partial
1180 // specialization from which it was instantiated.
1181 if (ClassTemplateSpecializationDecl *SpecRD =
1182 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1183 llvm::PointerUnion<ClassTemplateDecl*,
1184 ClassTemplatePartialSpecializationDecl*> From =
1185 SpecRD->getInstantiatedFrom();
1186 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1187 Entity = FromTemplate->getTemplatedDecl();
1188 else if (From)
1189 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1190 // Otherwise, it's an explicit specialization.
1191 } else if (MemberSpecializationInfo *MSInfo =
1192 RD->getMemberSpecializationInfo())
1193 Entity = getInstantiatedFrom(RD, MSInfo);
1194 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1195 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1196 Entity = getInstantiatedFrom(ED, MSInfo);
1197 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1198 // FIXME: Map from variable template specializations back to the template.
1199 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1200 Entity = getInstantiatedFrom(VD, MSInfo);
1201 }
1202
1203 // Walk up to the containing context. That might also have been instantiated
1204 // from a template.
1205 DeclContext *Context = Entity->getDeclContext();
1206 if (Context->isFileContext())
1207 return Entity->getOwningModule();
1208 return getDefiningModule(cast<Decl>(Context));
1209}
1210
1211llvm::DenseSet<Module*> &Sema::getLookupModules() {
1212 unsigned N = ActiveTemplateInstantiations.size();
1213 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1214 I != N; ++I) {
1215 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1216 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001217 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001218 ActiveTemplateInstantiationLookupModules.push_back(M);
1219 }
1220 return LookupModulesCache;
1221}
1222
1223/// \brief Determine whether a declaration is visible to name lookup.
1224///
1225/// This routine determines whether the declaration D is visible in the current
1226/// lookup context, taking into account the current template instantiation
1227/// stack. During template instantiation, a declaration is visible if it is
1228/// visible from a module containing any entity on the template instantiation
1229/// path (by instantiating a template, you allow it to see the declarations that
1230/// your module can see, including those later on in your module).
1231bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1232 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1233 "should not call this: not in slow case");
1234 Module *DeclModule = D->getOwningModule();
1235 assert(DeclModule && "hidden decl not from a module");
1236
1237 // Find the extra places where we need to look.
1238 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1239 if (LookupModules.empty())
1240 return false;
1241
1242 // If our lookup set contains the decl's module, it's visible.
1243 if (LookupModules.count(DeclModule))
1244 return true;
1245
1246 // If the declaration isn't exported, it's not visible in any other module.
1247 if (D->isModulePrivate())
1248 return false;
1249
1250 // Check whether DeclModule is transitively exported to an import of
1251 // the lookup set.
1252 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1253 E = LookupModules.end();
1254 I != E; ++I)
1255 if ((*I)->isModuleVisible(DeclModule))
1256 return true;
1257 return false;
1258}
1259
Douglas Gregor4a814562011-12-14 16:03:29 +00001260/// \brief Retrieve the visible declaration corresponding to D, if any.
1261///
1262/// This routine determines whether the declaration D is visible in the current
1263/// module, with the current imports. If not, it checks whether any
1264/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001265///
Douglas Gregor4a814562011-12-14 16:03:29 +00001266/// \returns D, or a visible previous declaration of D, whichever is more recent
1267/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001268static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1269 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001270
Aaron Ballman86c93902014-03-06 23:45:36 +00001271 for (auto RD : D->redecls()) {
1272 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe156254d2013-08-20 20:35:18 +00001273 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001274 return ND;
1275 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001276 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001277
Craig Topperc3ec1492014-05-26 06:22:03 +00001278 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001279}
1280
Richard Smithe156254d2013-08-20 20:35:18 +00001281NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1282 return findAcceptableDecl(SemaRef, D);
1283}
1284
Douglas Gregor34074322009-01-14 22:20:51 +00001285/// @brief Perform unqualified name lookup starting from a given
1286/// scope.
1287///
1288/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1289/// used to find names within the current scope. For example, 'x' in
1290/// @code
1291/// int x;
1292/// int f() {
1293/// return x; // unqualified name look finds 'x' in the global scope
1294/// }
1295/// @endcode
1296///
1297/// Different lookup criteria can find different names. For example, a
1298/// particular scope can have both a struct and a function of the same
1299/// name, and each can be found by certain lookup criteria. For more
1300/// information about lookup criteria, see the documentation for the
1301/// class LookupCriteria.
1302///
1303/// @param S The scope from which unqualified name lookup will
1304/// begin. If the lookup criteria permits, name lookup may also search
1305/// in the parent scopes.
1306///
James Dennett91738ff2012-06-22 10:32:46 +00001307/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1308/// look up and the lookup kind), and is updated with the results of lookup
1309/// including zero or more declarations and possibly additional information
1310/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001311///
James Dennett91738ff2012-06-22 10:32:46 +00001312/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001313bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1314 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001315 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001316
John McCall27b18f82009-11-17 02:14:36 +00001317 LookupNameKind NameKind = R.getLookupKind();
1318
David Blaikiebbafb8a2012-03-11 07:00:24 +00001319 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001320 // Unqualified name lookup in C/Objective-C is purely lexical, so
1321 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001322 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001323 // Find the nearest non-transparent declaration scope.
1324 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001325 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001326 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001327 }
1328
Richard Smith541b38b2013-09-20 01:15:31 +00001329 // When performing a scope lookup, we want to find local extern decls.
1330 FindLocalExternScope FindLocals(R);
1331
Douglas Gregor34074322009-01-14 22:20:51 +00001332 // Scan up the scope chain looking for a decl that matches this
1333 // identifier that is in the appropriate namespace. This search
1334 // should not take long, as shadowing of names is uncommon, and
1335 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001336 bool LeftStartingScope = false;
1337
Douglas Gregored8f2882009-01-30 01:04:22 +00001338 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001339 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001340 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001341 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001342 if (NameKind == LookupRedeclarationWithLinkage) {
1343 // Determine whether this (or a previous) declaration is
1344 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001345 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001346 LeftStartingScope = true;
1347
1348 // If we found something outside of our starting scope that
1349 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001350 if (LeftStartingScope && !((*I)->hasLinkage())) {
1351 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001352 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001353 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001354 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001355 else if (NameKind == LookupObjCImplicitSelfParam &&
1356 !isa<ImplicitParamDecl>(*I))
1357 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001358
Douglas Gregor4a814562011-12-14 16:03:29 +00001359 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001360
Douglas Gregorb59643b2012-01-03 23:26:26 +00001361 // Check whether there are any other declarations with the same name
1362 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001363 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001364 // Find the scope in which this declaration was declared (if it
1365 // actually exists in a Scope).
1366 while (S && !S->isDeclScope(D))
1367 S = S->getParent();
1368
1369 // If the scope containing the declaration is the translation unit,
1370 // then we'll need to perform our checks based on the matching
1371 // DeclContexts rather than matching scopes.
1372 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001373 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001374
1375 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001376 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001377 if (!S)
1378 DC = (*I)->getDeclContext()->getRedeclContext();
1379
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001380 IdentifierResolver::iterator LastI = I;
1381 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001382 if (S) {
1383 // Match based on scope.
1384 if (!S->isDeclScope(*LastI))
1385 break;
1386 } else {
1387 // Match based on DeclContext.
1388 DeclContext *LastDC
1389 = (*LastI)->getDeclContext()->getRedeclContext();
1390 if (!LastDC->Equals(DC))
1391 break;
1392 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001393
1394 // If the declaration is in the right namespace and visible, add it.
1395 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1396 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001397 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001398
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001399 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001400 }
Richard Smith541b38b2013-09-20 01:15:31 +00001401
John McCall9f3059a2009-10-09 21:13:30 +00001402 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001403 }
Douglas Gregor34074322009-01-14 22:20:51 +00001404 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001405 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001406 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001407 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001408 }
1409
1410 // If we didn't find a use of this identifier, and if the identifier
1411 // corresponds to a compiler builtin, create the decl object for the builtin
1412 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001413 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1414 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001415
Axel Naumann016538a2011-02-24 16:47:47 +00001416 // If we didn't find a use of this identifier, the ExternalSource
1417 // may be able to handle the situation.
1418 // Note: some lookup failures are expected!
1419 // See e.g. R.isForRedeclaration().
1420 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001421}
1422
John McCall6538c932009-10-10 05:48:19 +00001423/// @brief Perform qualified name lookup in the namespaces nominated by
1424/// using directives by the given context.
1425///
1426/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001427/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001428/// (where X is the global namespace), let S be the set of all
1429/// declarations of m in X and in the transitive closure of all
1430/// namespaces nominated by using-directives in X and its used
1431/// namespaces, except that using-directives are ignored in any
1432/// namespace, including X, directly containing one or more
1433/// declarations of m. No namespace is searched more than once in
1434/// the lookup of a name. If S is the empty set, the program is
1435/// ill-formed. Otherwise, if S has exactly one member, or if the
1436/// context of the reference is a using-declaration
1437/// (namespace.udecl), S is the required set of declarations of
1438/// m. Otherwise if the use of m is not one that allows a unique
1439/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001440///
John McCall6538c932009-10-10 05:48:19 +00001441/// C++98 [namespace.qual]p5:
1442/// During the lookup of a qualified namespace member name, if the
1443/// lookup finds more than one declaration of the member, and if one
1444/// declaration introduces a class name or enumeration name and the
1445/// other declarations either introduce the same object, the same
1446/// enumerator or a set of functions, the non-type name hides the
1447/// class or enumeration name if and only if the declarations are
1448/// from the same namespace; otherwise (the declarations are from
1449/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001450static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001451 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001452 assert(StartDC->isFileContext() && "start context is not a file context");
1453
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001454 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1455 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001456
1457 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001458 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001459 Visited.insert(StartDC);
1460
1461 // We have not yet looked into these namespaces, much less added
1462 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001463 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001464
1465 // We have already looked into the initial namespace; seed the queue
1466 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001467 for (auto *I : UsingDirectives) {
1468 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001469 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001470 Queue.push_back(ND);
1471 }
1472
1473 // The easiest way to implement the restriction in [namespace.qual]p5
1474 // is to check whether any of the individual results found a tag
1475 // and, if so, to declare an ambiguity if the final result is not
1476 // a tag.
1477 bool FoundTag = false;
1478 bool FoundNonTag = false;
1479
John McCall5cebab12009-11-18 07:57:50 +00001480 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001481
1482 bool Found = false;
1483 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001484 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001485
1486 // We go through some convolutions here to avoid copying results
1487 // between LookupResults.
1488 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001489 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001490 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001491
1492 if (FoundDirect) {
1493 // First do any local hiding.
1494 DirectR.resolveKind();
1495
1496 // If the local result is a tag, remember that.
1497 if (DirectR.isSingleTagDecl())
1498 FoundTag = true;
1499 else
1500 FoundNonTag = true;
1501
1502 // Append the local results to the total results if necessary.
1503 if (UseLocal) {
1504 R.addAllDecls(LocalR);
1505 LocalR.clear();
1506 }
1507 }
1508
1509 // If we find names in this namespace, ignore its using directives.
1510 if (FoundDirect) {
1511 Found = true;
1512 continue;
1513 }
1514
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001515 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001516 NamespaceDecl *Nom = I->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001517 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001518 Queue.push_back(Nom);
1519 }
1520 }
1521
1522 if (Found) {
1523 if (FoundTag && FoundNonTag)
1524 R.setAmbiguousQualifiedTagHiding();
1525 else
1526 R.resolveKind();
1527 }
1528
1529 return Found;
1530}
1531
Douglas Gregor39982192010-08-15 06:18:01 +00001532/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001533static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001534 CXXBasePath &Path,
1535 void *Name) {
1536 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001537
Douglas Gregor39982192010-08-15 06:18:01 +00001538 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1539 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001540 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001541}
1542
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001543/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001544/// static members, nested types, and enumerators.
1545template<typename InputIterator>
1546static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1547 Decl *D = (*First)->getUnderlyingDecl();
1548 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1549 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001550
Douglas Gregorc0d24902010-10-22 22:08:47 +00001551 if (isa<CXXMethodDecl>(D)) {
1552 // Determine whether all of the methods are static.
1553 bool AllMethodsAreStatic = true;
1554 for(; First != Last; ++First) {
1555 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556
Douglas Gregorc0d24902010-10-22 22:08:47 +00001557 if (!isa<CXXMethodDecl>(D)) {
1558 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1559 break;
1560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001561
Douglas Gregorc0d24902010-10-22 22:08:47 +00001562 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1563 AllMethodsAreStatic = false;
1564 break;
1565 }
1566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001567
Douglas Gregorc0d24902010-10-22 22:08:47 +00001568 if (AllMethodsAreStatic)
1569 return true;
1570 }
1571
1572 return false;
1573}
1574
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001575/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001576///
1577/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1578/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001579/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001580///
1581/// Different lookup criteria can find different names. For example, a
1582/// particular scope can have both a struct and a function of the same
1583/// name, and each can be found by certain lookup criteria. For more
1584/// information about lookup criteria, see the documentation for the
1585/// class LookupCriteria.
1586///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001587/// \param R captures both the lookup criteria and any lookup results found.
1588///
1589/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001590/// search. If the lookup criteria permits, name lookup may also search
1591/// in the parent contexts or (for C++ classes) base classes.
1592///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001593/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001594/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001595///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001596/// \returns true if lookup succeeded, false if it failed.
1597bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1598 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001599 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001600
John McCall27b18f82009-11-17 02:14:36 +00001601 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001602 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001603
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001604 // Make sure that the declaration context is complete.
1605 assert((!isa<TagDecl>(LookupCtx) ||
1606 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001607 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001608 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001609 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001610
Douglas Gregor34074322009-01-14 22:20:51 +00001611 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001612 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001613 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001614 if (isa<CXXRecordDecl>(LookupCtx))
1615 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001616 return true;
1617 }
Douglas Gregor34074322009-01-14 22:20:51 +00001618
John McCall6538c932009-10-10 05:48:19 +00001619 // Don't descend into implied contexts for redeclarations.
1620 // C++98 [namespace.qual]p6:
1621 // In a declaration for a namespace member in which the
1622 // declarator-id is a qualified-id, given that the qualified-id
1623 // for the namespace member has the form
1624 // nested-name-specifier unqualified-id
1625 // the unqualified-id shall name a member of the namespace
1626 // designated by the nested-name-specifier.
1627 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001628 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001629 return false;
1630
John McCall27b18f82009-11-17 02:14:36 +00001631 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001632 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001633 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001634
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001635 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001636 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001637 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001638 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001639 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001640
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001641 // If we're performing qualified name lookup into a dependent class,
1642 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001643 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001644 // template instantiation time (at which point all bases will be available)
1645 // or we have to fail.
1646 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1647 LookupRec->hasAnyDependentBases()) {
1648 R.setNotFoundInCurrentInstantiation();
1649 return false;
1650 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001651
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001652 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001653 CXXBasePaths Paths;
1654 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001655
1656 // Look for this member in our base classes
Craig Topperc3ec1492014-05-26 06:22:03 +00001657 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001658 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001659 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001660 case LookupOrdinaryName:
1661 case LookupMemberName:
1662 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001663 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001664 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1665 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666
Douglas Gregor36d1b142009-10-06 17:59:45 +00001667 case LookupTagName:
1668 BaseCallback = &CXXRecordDecl::FindTagMember;
1669 break;
John McCall84d87672009-12-10 09:41:52 +00001670
Douglas Gregor39982192010-08-15 06:18:01 +00001671 case LookupAnyName:
1672 BaseCallback = &LookupAnyMember;
1673 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
John McCall84d87672009-12-10 09:41:52 +00001675 case LookupUsingDeclName:
1676 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001677
Douglas Gregor36d1b142009-10-06 17:59:45 +00001678 case LookupOperatorName:
1679 case LookupNamespaceName:
1680 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001681 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001682 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001683 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001684
Douglas Gregor36d1b142009-10-06 17:59:45 +00001685 case LookupNestedNameSpecifierName:
1686 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1687 break;
1688 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001689
John McCall27b18f82009-11-17 02:14:36 +00001690 if (!LookupRec->lookupInBases(BaseCallback,
1691 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001692 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001693
John McCall553c0792010-01-23 00:46:32 +00001694 R.setNamingClass(LookupRec);
1695
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001696 // C++ [class.member.lookup]p2:
1697 // [...] If the resulting set of declarations are not all from
1698 // sub-objects of the same type, or the set has a nonstatic member
1699 // and includes members from distinct sub-objects, there is an
1700 // ambiguity and the program is ill-formed. Otherwise that set is
1701 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001702 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001703 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001704 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001705
Douglas Gregor36d1b142009-10-06 17:59:45 +00001706 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001707 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001708 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001709
John McCall401982f2010-01-20 21:53:11 +00001710 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1711 // across all paths.
1712 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001713
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001714 // Determine whether we're looking at a distinct sub-object or not.
1715 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001716 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001717 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1718 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001719 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001720 }
1721
Douglas Gregorc0d24902010-10-22 22:08:47 +00001722 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001723 != Context.getCanonicalType(PathElement.Base->getType())) {
1724 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001725 // different types. If the declaration sets aren't the same, this
1726 // this lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001727 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001728 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001729 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1730 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731
David Blaikieff7d47a2012-12-19 00:45:41 +00001732 while (FirstD != FirstPath->Decls.end() &&
1733 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001734 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1735 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737
Douglas Gregorc0d24902010-10-22 22:08:47 +00001738 ++FirstD;
1739 ++CurrentD;
1740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001741
David Blaikieff7d47a2012-12-19 00:45:41 +00001742 if (FirstD == FirstPath->Decls.end() &&
1743 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001744 continue;
1745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746
John McCall9f3059a2009-10-09 21:13:30 +00001747 R.setAmbiguousBaseSubobjectTypes(Paths);
1748 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001749 }
1750
Douglas Gregorc0d24902010-10-22 22:08:47 +00001751 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001752 // We have a different subobject of the same type.
1753
1754 // C++ [class.member.lookup]p5:
1755 // A static member, a nested type or an enumerator defined in
1756 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001757 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001758 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001759 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001760
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001761 // We have found a nonstatic member name in multiple, distinct
1762 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001763 R.setAmbiguousBaseSubobjects(Paths);
1764 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001765 }
1766 }
1767
1768 // Lookup in a base class succeeded; return these results.
1769
David Blaikieff7d47a2012-12-19 00:45:41 +00001770 DeclContext::lookup_result DR = Paths.front().Decls;
1771 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall553c0792010-01-23 00:46:32 +00001772 NamedDecl *D = *I;
1773 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1774 D->getAccess());
1775 R.addDecl(D, AS);
1776 }
John McCall9f3059a2009-10-09 21:13:30 +00001777 R.resolveKind();
1778 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001779}
1780
1781/// @brief Performs name lookup for a name that was parsed in the
1782/// source code, and may contain a C++ scope specifier.
1783///
1784/// This routine is a convenience routine meant to be called from
1785/// contexts that receive a name and an optional C++ scope specifier
1786/// (e.g., "N::M::x"). It will then perform either qualified or
1787/// unqualified name lookup (with LookupQualifiedName or LookupName,
1788/// respectively) on the given name and return those results.
1789///
1790/// @param S The scope from which unqualified name lookup will
1791/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001792///
Douglas Gregore861bac2009-08-25 22:51:20 +00001793/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001794///
Douglas Gregore861bac2009-08-25 22:51:20 +00001795/// @param EnteringContext Indicates whether we are going to enter the
1796/// context of the scope-specifier SS (if present).
1797///
John McCall9f3059a2009-10-09 21:13:30 +00001798/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001799bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001800 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001801 if (SS && SS->isInvalid()) {
1802 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001803 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001804 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001805 }
Mike Stump11289f42009-09-09 15:08:12 +00001806
Douglas Gregore861bac2009-08-25 22:51:20 +00001807 if (SS && SS->isSet()) {
1808 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001809 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001810 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001811 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001812 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001813
John McCall27b18f82009-11-17 02:14:36 +00001814 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001815 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001816 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001817
Douglas Gregore861bac2009-08-25 22:51:20 +00001818 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001819 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001820 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001821 R.setNotFoundInCurrentInstantiation();
1822 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001823 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001824 }
1825
Mike Stump11289f42009-09-09 15:08:12 +00001826 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001827 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001828}
1829
Douglas Gregor889ceb72009-02-03 19:21:40 +00001830
James Dennett41725122012-06-22 10:16:05 +00001831/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001832/// from name lookup.
1833///
James Dennett41725122012-06-22 10:16:05 +00001834/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001835void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001836 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1837
John McCall27b18f82009-11-17 02:14:36 +00001838 DeclarationName Name = Result.getLookupName();
1839 SourceLocation NameLoc = Result.getNameLoc();
1840 SourceRange LookupRange = Result.getContextRange();
1841
John McCall6538c932009-10-10 05:48:19 +00001842 switch (Result.getAmbiguityKind()) {
1843 case LookupResult::AmbiguousBaseSubobjects: {
1844 CXXBasePaths *Paths = Result.getBasePaths();
1845 QualType SubobjectType = Paths->front().back().Base->getType();
1846 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1847 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1848 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849
David Blaikieff7d47a2012-12-19 00:45:41 +00001850 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001851 while (isa<CXXMethodDecl>(*Found) &&
1852 cast<CXXMethodDecl>(*Found)->isStatic())
1853 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001854
John McCall6538c932009-10-10 05:48:19 +00001855 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001856 break;
John McCall6538c932009-10-10 05:48:19 +00001857 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001858
John McCall6538c932009-10-10 05:48:19 +00001859 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001860 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1861 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
John McCall6538c932009-10-10 05:48:19 +00001863 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001864 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001865 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1866 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001867 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001868 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001869 if (DeclsPrinted.insert(D).second)
1870 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1871 }
Serge Pavlov99292092013-08-29 07:23:24 +00001872 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001873 }
1874
John McCall6538c932009-10-10 05:48:19 +00001875 case LookupResult::AmbiguousTagHiding: {
1876 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001877
John McCall6538c932009-10-10 05:48:19 +00001878 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1879
1880 LookupResult::iterator DI, DE = Result.end();
1881 for (DI = Result.begin(); DI != DE; ++DI)
1882 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1883 TagDecls.insert(TD);
1884 Diag(TD->getLocation(), diag::note_hidden_tag);
1885 }
1886
1887 for (DI = Result.begin(); DI != DE; ++DI)
1888 if (!isa<TagDecl>(*DI))
1889 Diag((*DI)->getLocation(), diag::note_hiding_object);
1890
1891 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001892 LookupResult::Filter F = Result.makeFilter();
1893 while (F.hasNext()) {
1894 if (TagDecls.count(F.next()))
1895 F.erase();
1896 }
1897 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001898 break;
John McCall6538c932009-10-10 05:48:19 +00001899 }
1900
1901 case LookupResult::AmbiguousReference: {
1902 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903
John McCall6538c932009-10-10 05:48:19 +00001904 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1905 for (; DI != DE; ++DI)
1906 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov99292092013-08-29 07:23:24 +00001907 break;
John McCall6538c932009-10-10 05:48:19 +00001908 }
Serge Pavlov99292092013-08-29 07:23:24 +00001909 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001910}
Douglas Gregore254f902009-02-04 00:32:51 +00001911
John McCallf24d7bb2010-05-28 18:45:08 +00001912namespace {
1913 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001914 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001915 Sema::AssociatedNamespaceSet &Namespaces,
1916 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001917 : S(S), Namespaces(Namespaces), Classes(Classes),
1918 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001919 }
1920
1921 Sema &S;
1922 Sema::AssociatedNamespaceSet &Namespaces;
1923 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001924 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001925 };
1926}
1927
Mike Stump11289f42009-09-09 15:08:12 +00001928static void
John McCallf24d7bb2010-05-28 18:45:08 +00001929addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001930
Douglas Gregor8b895222010-04-30 07:08:38 +00001931static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1932 DeclContext *Ctx) {
1933 // Add the associated namespace for this class.
1934
1935 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1936 // be a locally scoped record.
1937
Sebastian Redlbd595762010-08-31 20:53:31 +00001938 // We skip out of inline namespaces. The innermost non-inline namespace
1939 // contains all names of all its nested inline namespaces anyway, so we can
1940 // replace the entire inline namespace tree with its root.
1941 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1942 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001943 Ctx = Ctx->getParent();
1944
John McCallc7e8e792009-08-07 22:18:02 +00001945 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001946 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001947}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001948
Mike Stump11289f42009-09-09 15:08:12 +00001949// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001950// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001951static void
John McCallf24d7bb2010-05-28 18:45:08 +00001952addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1953 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001954 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001955 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001956 switch (Arg.getKind()) {
1957 case TemplateArgument::Null:
1958 break;
Mike Stump11289f42009-09-09 15:08:12 +00001959
Douglas Gregor197e5f72009-07-08 07:51:57 +00001960 case TemplateArgument::Type:
1961 // [...] the namespaces and classes associated with the types of the
1962 // template arguments provided for template type parameters (excluding
1963 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001964 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001965 break;
Mike Stump11289f42009-09-09 15:08:12 +00001966
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001968 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001969 // [...] the namespaces in which any template template arguments are
1970 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001971 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001972 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001973 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001974 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001975 DeclContext *Ctx = ClassTemplate->getDeclContext();
1976 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001977 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001978 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001979 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001980 }
1981 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001983
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001984 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001985 case TemplateArgument::Integral:
1986 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00001987 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00001988 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001989 // associated namespaces. ]
1990 break;
Mike Stump11289f42009-09-09 15:08:12 +00001991
Douglas Gregor197e5f72009-07-08 07:51:57 +00001992 case TemplateArgument::Pack:
1993 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1994 PEnd = Arg.pack_end();
1995 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001996 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001997 break;
1998 }
1999}
2000
Douglas Gregore254f902009-02-04 00:32:51 +00002001// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002002// argument-dependent lookup with an argument of class type
2003// (C++ [basic.lookup.koenig]p2).
2004static void
John McCallf24d7bb2010-05-28 18:45:08 +00002005addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2006 CXXRecordDecl *Class) {
2007
2008 // Just silently ignore anything whose name is __va_list_tag.
2009 if (Class->getDeclName() == Result.S.VAListTagName)
2010 return;
2011
Douglas Gregore254f902009-02-04 00:32:51 +00002012 // C++ [basic.lookup.koenig]p2:
2013 // [...]
2014 // -- If T is a class type (including unions), its associated
2015 // classes are: the class itself; the class of which it is a
2016 // member, if any; and its direct and indirect base
2017 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002018 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002019
2020 // Add the class of which it is a member, if any.
2021 DeclContext *Ctx = Class->getDeclContext();
2022 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002023 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002024 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002025 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002026
Douglas Gregore254f902009-02-04 00:32:51 +00002027 // Add the class itself. If we've already seen this class, we don't
2028 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002029 //
2030 // FIXME: That's not correct, we may have added this class only because it
2031 // was the enclosing class of another class, and in that case we won't have
2032 // added its base classes yet.
John McCallf24d7bb2010-05-28 18:45:08 +00002033 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002034 return;
2035
Mike Stump11289f42009-09-09 15:08:12 +00002036 // -- If T is a template-id, its associated namespaces and classes are
2037 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002038 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002039 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002040 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002041 // namespaces in which any template template arguments are defined; and
2042 // the classes in which any member templates used as template template
2043 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002044 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002045 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002046 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2047 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2048 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002049 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002050 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002051 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002052
Douglas Gregor197e5f72009-07-08 07:51:57 +00002053 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2054 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002055 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002056 }
Mike Stump11289f42009-09-09 15:08:12 +00002057
John McCall67da35c2010-02-04 22:26:26 +00002058 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002059 if (!Class->hasDefinition())
2060 return;
John McCall67da35c2010-02-04 22:26:26 +00002061
Douglas Gregore254f902009-02-04 00:32:51 +00002062 // Add direct and indirect base classes along with their associated
2063 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002064 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002065 Bases.push_back(Class);
2066 while (!Bases.empty()) {
2067 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002068 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002069
2070 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002071 for (const auto &Base : Class->bases()) {
2072 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002073 // In dependent contexts, we do ADL twice, and the first time around,
2074 // the base type might be a dependent TemplateSpecializationType, or a
2075 // TemplateTypeParmType. If that happens, simply ignore it.
2076 // FIXME: If we want to support export, we probably need to add the
2077 // namespace of the template in a TemplateSpecializationType, or even
2078 // the classes and namespaces of known non-dependent arguments.
2079 if (!BaseType)
2080 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002081 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002082 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002083 // Find the associated namespace for this base class.
2084 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002085 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002086
2087 // Make sure we visit the bases of this base class.
2088 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2089 Bases.push_back(BaseDecl);
2090 }
2091 }
2092 }
2093}
2094
2095// \brief Add the associated classes and namespaces for
2096// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002097// (C++ [basic.lookup.koenig]p2).
2098static void
John McCallf24d7bb2010-05-28 18:45:08 +00002099addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002100 // C++ [basic.lookup.koenig]p2:
2101 //
2102 // For each argument type T in the function call, there is a set
2103 // of zero or more associated namespaces and a set of zero or more
2104 // associated classes to be considered. The sets of namespaces and
2105 // classes is determined entirely by the types of the function
2106 // arguments (and the namespace of any template template
2107 // argument). Typedef names and using-declarations used to specify
2108 // the types do not contribute to this set. The sets of namespaces
2109 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002110
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002111 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002112 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2113
Douglas Gregore254f902009-02-04 00:32:51 +00002114 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002115 switch (T->getTypeClass()) {
2116
2117#define TYPE(Class, Base)
2118#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2119#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2120#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2121#define ABSTRACT_TYPE(Class, Base)
2122#include "clang/AST/TypeNodes.def"
2123 // T is canonical. We can also ignore dependent types because
2124 // we don't need to do ADL at the definition point, but if we
2125 // wanted to implement template export (or if we find some other
2126 // use for associated classes and namespaces...) this would be
2127 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002128 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002129
John McCall0af3d3b2010-05-28 06:08:54 +00002130 // -- If T is a pointer to U or an array of U, its associated
2131 // namespaces and classes are those associated with U.
2132 case Type::Pointer:
2133 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2134 continue;
2135 case Type::ConstantArray:
2136 case Type::IncompleteArray:
2137 case Type::VariableArray:
2138 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2139 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002140
John McCall0af3d3b2010-05-28 06:08:54 +00002141 // -- If T is a fundamental type, its associated sets of
2142 // namespaces and classes are both empty.
2143 case Type::Builtin:
2144 break;
2145
2146 // -- If T is a class type (including unions), its associated
2147 // classes are: the class itself; the class of which it is a
2148 // member, if any; and its direct and indirect base
2149 // classes. Its associated namespaces are the namespaces in
2150 // which its associated classes are defined.
2151 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002152 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2153 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002154 CXXRecordDecl *Class
2155 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002156 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002157 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002158 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002159
John McCall0af3d3b2010-05-28 06:08:54 +00002160 // -- If T is an enumeration type, its associated namespace is
2161 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002162 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002163 // it has no associated class.
2164 case Type::Enum: {
2165 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002166
John McCall0af3d3b2010-05-28 06:08:54 +00002167 DeclContext *Ctx = Enum->getDeclContext();
2168 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002169 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002170
John McCall0af3d3b2010-05-28 06:08:54 +00002171 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002172 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002173
John McCall0af3d3b2010-05-28 06:08:54 +00002174 break;
2175 }
2176
2177 // -- If T is a function type, its associated namespaces and
2178 // classes are those associated with the function parameter
2179 // types and those associated with the return type.
2180 case Type::FunctionProto: {
2181 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002182 for (const auto &Arg : Proto->param_types())
2183 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002184 // fallthrough
2185 }
2186 case Type::FunctionNoProto: {
2187 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002188 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002189 continue;
2190 }
2191
2192 // -- If T is a pointer to a member function of a class X, its
2193 // associated namespaces and classes are those associated
2194 // with the function parameter types and return type,
2195 // together with those associated with X.
2196 //
2197 // -- If T is a pointer to a data member of class X, its
2198 // associated namespaces and classes are those associated
2199 // with the member type together with those associated with
2200 // X.
2201 case Type::MemberPointer: {
2202 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2203
2204 // Queue up the class type into which this points.
2205 Queue.push_back(MemberPtr->getClass());
2206
2207 // And directly continue with the pointee type.
2208 T = MemberPtr->getPointeeType().getTypePtr();
2209 continue;
2210 }
2211
2212 // As an extension, treat this like a normal pointer.
2213 case Type::BlockPointer:
2214 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2215 continue;
2216
2217 // References aren't covered by the standard, but that's such an
2218 // obvious defect that we cover them anyway.
2219 case Type::LValueReference:
2220 case Type::RValueReference:
2221 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2222 continue;
2223
2224 // These are fundamental types.
2225 case Type::Vector:
2226 case Type::ExtVector:
2227 case Type::Complex:
2228 break;
2229
Richard Smith27d807c2013-04-30 13:56:41 +00002230 // Non-deduced auto types only get here for error cases.
2231 case Type::Auto:
2232 break;
2233
Douglas Gregor8e936662011-04-12 01:02:45 +00002234 // If T is an Objective-C object or interface type, or a pointer to an
2235 // object or interface type, the associated namespace is the global
2236 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002237 case Type::ObjCObject:
2238 case Type::ObjCInterface:
2239 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002240 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002241 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002242
2243 // Atomic types are just wrappers; use the associations of the
2244 // contained type.
2245 case Type::Atomic:
2246 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2247 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002248 }
2249
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002250 if (Queue.empty())
2251 break;
2252 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002253 }
Douglas Gregore254f902009-02-04 00:32:51 +00002254}
2255
2256/// \brief Find the associated classes and namespaces for
2257/// argument-dependent lookup for a call with the given set of
2258/// arguments.
2259///
2260/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002261/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002262/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002263void Sema::FindAssociatedClassesAndNamespaces(
2264 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2265 AssociatedNamespaceSet &AssociatedNamespaces,
2266 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002267 AssociatedNamespaces.clear();
2268 AssociatedClasses.clear();
2269
John McCall7d8b0412012-08-24 20:38:34 +00002270 AssociatedLookup Result(*this, InstantiationLoc,
2271 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002272
Douglas Gregore254f902009-02-04 00:32:51 +00002273 // C++ [basic.lookup.koenig]p2:
2274 // For each argument type T in the function call, there is a set
2275 // of zero or more associated namespaces and a set of zero or more
2276 // associated classes to be considered. The sets of namespaces and
2277 // classes is determined entirely by the types of the function
2278 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002279 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002280 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002281 Expr *Arg = Args[ArgIdx];
2282
2283 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002284 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002285 continue;
2286 }
2287
2288 // [...] In addition, if the argument is the name or address of a
2289 // set of overloaded functions and/or function templates, its
2290 // associated classes and namespaces are the union of those
2291 // associated with each of the members of the set: the namespace
2292 // in which the function or function template is defined and the
2293 // classes and namespaces associated with its (non-dependent)
2294 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002295 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002296 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002297 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002298 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002299
John McCallf24d7bb2010-05-28 18:45:08 +00002300 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2301 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002302
John McCallf24d7bb2010-05-28 18:45:08 +00002303 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2304 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002305 // Look through any using declarations to find the underlying function.
Alp Tokera2794f92014-01-22 07:29:52 +00002306 FunctionDecl *FDecl = (*I)->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002307
2308 // Add the classes and namespaces associated with the parameter
2309 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002310 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002311 }
2312 }
2313}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002314
John McCall5cebab12009-11-18 07:57:50 +00002315NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002316 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002317 LookupNameKind NameKind,
2318 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002319 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002320 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002321 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002322}
2323
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002324/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002325ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002326 SourceLocation IdLoc,
2327 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002328 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002329 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002330 return cast_or_null<ObjCProtocolDecl>(D);
2331}
2332
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002333void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002334 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002335 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002336 // C++ [over.match.oper]p3:
2337 // -- The set of non-member candidates is the result of the
2338 // unqualified lookup of operator@ in the context of the
2339 // expression according to the usual rules for name lookup in
2340 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002341 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002342 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002343 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2344 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002345
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002346 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002347 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002348}
2349
Alexis Hunt1da39282011-06-24 02:11:39 +00002350Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002351 CXXSpecialMember SM,
2352 bool ConstArg,
2353 bool VolatileArg,
2354 bool RValueThis,
2355 bool ConstThis,
2356 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002357 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002358 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002359 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002360 if (RValueThis || ConstThis || VolatileThis)
2361 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2362 "constructors and destructors always have unqualified lvalue this");
2363 if (ConstArg || VolatileArg)
2364 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2365 "parameter-less special members can't have qualified arguments");
2366
2367 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002368 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002369 ID.AddInteger(SM);
2370 ID.AddInteger(ConstArg);
2371 ID.AddInteger(VolatileArg);
2372 ID.AddInteger(RValueThis);
2373 ID.AddInteger(ConstThis);
2374 ID.AddInteger(VolatileThis);
2375
2376 void *InsertPoint;
2377 SpecialMemberOverloadResult *Result =
2378 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2379
2380 // This was already cached
2381 if (Result)
2382 return Result;
2383
Alexis Huntba8e18d2011-06-07 00:11:58 +00002384 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2385 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002386 SpecialMemberCache.InsertNode(Result, InsertPoint);
2387
2388 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002389 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002390 DeclareImplicitDestructor(RD);
2391 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002392 assert(DD && "record without a destructor");
2393 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002394 Result->setKind(DD->isDeleted() ?
2395 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002396 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002397 return Result;
2398 }
2399
Alexis Hunteef8ee02011-06-10 03:50:41 +00002400 // Prepare for overload resolution. Here we construct a synthetic argument
2401 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002402 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002403 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002404 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002405 unsigned NumArgs;
2406
Richard Smith83c478d2012-04-20 18:46:14 +00002407 QualType ArgType = CanTy;
2408 ExprValueKind VK = VK_LValue;
2409
Alexis Hunteef8ee02011-06-10 03:50:41 +00002410 if (SM == CXXDefaultConstructor) {
2411 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2412 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002413 if (RD->needsImplicitDefaultConstructor())
2414 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002415 } else {
2416 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2417 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002418 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002419 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002420 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002421 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002422 } else {
2423 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002424 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002425 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002426 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002427 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002428 }
2429
Alexis Hunteef8ee02011-06-10 03:50:41 +00002430 if (ConstArg)
2431 ArgType.addConst();
2432 if (VolatileArg)
2433 ArgType.addVolatile();
2434
2435 // This isn't /really/ specified by the standard, but it's implied
2436 // we should be working from an RValue in the case of move to ensure
2437 // that we prefer to bind to rvalue references, and an LValue in the
2438 // case of copy to ensure we don't bind to rvalue references.
2439 // Possibly an XValue is actually correct in the case of move, but
2440 // there is no semantic difference for class types in this restricted
2441 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002442 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002443 VK = VK_LValue;
2444 else
2445 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002446 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002447
Richard Smith83c478d2012-04-20 18:46:14 +00002448 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2449
2450 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002451 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002452 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002453 }
2454
2455 // Create the object argument
2456 QualType ThisTy = CanTy;
2457 if (ConstThis)
2458 ThisTy.addConst();
2459 if (VolatileThis)
2460 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002461 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002462 OpaqueValueExpr(SourceLocation(), ThisTy,
2463 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002464
2465 // Now we perform lookup on the name we computed earlier and do overload
2466 // resolution. Lookup is only performed directly into the class since there
2467 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002468 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002469 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00002470 assert(!R.empty() &&
Alexis Hunteef8ee02011-06-10 03:50:41 +00002471 "lookup for a constructor or assignment operator was empty");
Chandler Carruth7deaae72013-08-18 07:20:52 +00002472
2473 // Copy the candidates as our processing of them may load new declarations
2474 // from an external source and invalidate lookup_result.
2475 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2476
2477 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithd55889a2013-09-09 16:55:27 +00002478 E = Candidates.end();
Chandler Carruth7deaae72013-08-18 07:20:52 +00002479 I != E; ++I) {
2480 NamedDecl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002481
Alexis Hunt1da39282011-06-24 02:11:39 +00002482 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002483 continue;
2484
Alexis Hunt1da39282011-06-24 02:11:39 +00002485 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2486 // FIXME: [namespace.udecl]p15 says that we should only consider a
2487 // using declaration here if it does not match a declaration in the
2488 // derived class. We do not implement this correctly in other cases
2489 // either.
2490 Cand = U->getTargetDecl();
2491
2492 if (Cand->isInvalidDecl())
2493 continue;
2494 }
2495
2496 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002497 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002498 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002499 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2500 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002501 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002502 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2503 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002504 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002505 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002506 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2507 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002508 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002509 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002510 OCS, true);
2511 else
2512 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002513 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002514 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002515 } else {
2516 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002517 }
2518 }
2519
2520 OverloadCandidateSet::iterator Best;
2521 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2522 case OR_Success:
2523 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002524 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002525 break;
2526
2527 case OR_Deleted:
2528 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002529 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002530 break;
2531
2532 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002533 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002534 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2535 break;
2536
Alexis Hunteef8ee02011-06-10 03:50:41 +00002537 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002538 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002539 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002540 break;
2541 }
2542
2543 return Result;
2544}
2545
2546/// \brief Look up the default constructor for the given class.
2547CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002548 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002549 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2550 false, false);
2551
2552 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002553}
2554
Alexis Hunt491ec602011-06-21 23:42:56 +00002555/// \brief Look up the copying constructor for the given class.
2556CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002557 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002558 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2559 "non-const, non-volatile qualifiers for copy ctor arg");
2560 SpecialMemberOverloadResult *Result =
2561 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2562 Quals & Qualifiers::Volatile, false, false, false);
2563
Alexis Hunt899bd442011-06-10 04:44:37 +00002564 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2565}
2566
Sebastian Redl22653ba2011-08-30 19:58:05 +00002567/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002568CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2569 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002570 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002571 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2572 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002573
2574 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2575}
2576
Douglas Gregor52b72822010-07-02 23:12:18 +00002577/// \brief Look up the constructors for the given class.
2578DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002579 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002580 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002581 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002582 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002583 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002584 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002585 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002586 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002587 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002588
Douglas Gregor52b72822010-07-02 23:12:18 +00002589 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2590 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2591 return Class->lookup(Name);
2592}
2593
Alexis Hunt491ec602011-06-21 23:42:56 +00002594/// \brief Look up the copying assignment operator for the given class.
2595CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2596 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002597 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002598 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2599 "non-const, non-volatile qualifiers for copy assignment arg");
2600 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2601 "non-const, non-volatile qualifiers for copy assignment this");
2602 SpecialMemberOverloadResult *Result =
2603 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2604 Quals & Qualifiers::Volatile, RValueThis,
2605 ThisQuals & Qualifiers::Const,
2606 ThisQuals & Qualifiers::Volatile);
2607
Alexis Hunt491ec602011-06-21 23:42:56 +00002608 return Result->getMethod();
2609}
2610
Sebastian Redl22653ba2011-08-30 19:58:05 +00002611/// \brief Look up the moving assignment operator for the given class.
2612CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002613 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002614 bool RValueThis,
2615 unsigned ThisQuals) {
2616 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2617 "non-const, non-volatile qualifiers for copy assignment this");
2618 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002619 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2620 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002621 ThisQuals & Qualifiers::Const,
2622 ThisQuals & Qualifiers::Volatile);
2623
2624 return Result->getMethod();
2625}
2626
Douglas Gregore71edda2010-07-01 22:47:18 +00002627/// \brief Look for the destructor of the given class.
2628///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002629/// During semantic analysis, this routine should be used in lieu of
2630/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002631///
2632/// \returns The destructor for this class.
2633CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002634 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2635 false, false, false,
2636 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002637}
2638
Richard Smithbcc22fc2012-03-09 08:00:36 +00002639/// LookupLiteralOperator - Determine which literal operator should be used for
2640/// a user-defined literal, per C++11 [lex.ext].
2641///
2642/// Normal overload resolution is not used to select which literal operator to
2643/// call for a user-defined literal. Look up the provided literal operator name,
2644/// and filter the results to the appropriate set for the given argument types.
2645Sema::LiteralOperatorLookupResult
2646Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2647 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002648 bool AllowRaw, bool AllowTemplate,
2649 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002650 LookupName(R, S);
2651 assert(R.getResultKind() != LookupResult::Ambiguous &&
2652 "literal operator lookup can't be ambiguous");
2653
2654 // Filter the lookup results appropriately.
2655 LookupResult::Filter F = R.makeFilter();
2656
Richard Smithbcc22fc2012-03-09 08:00:36 +00002657 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002658 bool FoundTemplate = false;
2659 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002660 bool FoundExactMatch = false;
2661
2662 while (F.hasNext()) {
2663 Decl *D = F.next();
2664 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2665 D = USD->getTargetDecl();
2666
Douglas Gregorc1970572013-04-10 05:18:00 +00002667 // If the declaration we found is invalid, skip it.
2668 if (D->isInvalidDecl()) {
2669 F.erase();
2670 continue;
2671 }
2672
Richard Smithb8b41d32013-10-07 19:57:58 +00002673 bool IsRaw = false;
2674 bool IsTemplate = false;
2675 bool IsStringTemplate = false;
2676 bool IsExactMatch = false;
2677
Richard Smithbcc22fc2012-03-09 08:00:36 +00002678 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2679 if (FD->getNumParams() == 1 &&
2680 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2681 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002682 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002683 IsExactMatch = true;
2684 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2685 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2686 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2687 IsExactMatch = false;
2688 break;
2689 }
2690 }
2691 }
2692 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002693 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2694 TemplateParameterList *Params = FD->getTemplateParameters();
2695 if (Params->size() == 1)
2696 IsTemplate = true;
2697 else
2698 IsStringTemplate = true;
2699 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002700
2701 if (IsExactMatch) {
2702 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002703 AllowRaw = false;
2704 AllowTemplate = false;
2705 AllowStringTemplate = false;
2706 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002707 // Go through again and remove the raw and template decls we've
2708 // already found.
2709 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002710 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002711 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002712 } else if (AllowRaw && IsRaw) {
2713 FoundRaw = true;
2714 } else if (AllowTemplate && IsTemplate) {
2715 FoundTemplate = true;
2716 } else if (AllowStringTemplate && IsStringTemplate) {
2717 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002718 } else {
2719 F.erase();
2720 }
2721 }
2722
2723 F.done();
2724
2725 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2726 // parameter type, that is used in preference to a raw literal operator
2727 // or literal operator template.
2728 if (FoundExactMatch)
2729 return LOLR_Cooked;
2730
2731 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2732 // operator template, but not both.
2733 if (FoundRaw && FoundTemplate) {
2734 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002735 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2736 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002737 return LOLR_Error;
2738 }
2739
2740 if (FoundRaw)
2741 return LOLR_Raw;
2742
2743 if (FoundTemplate)
2744 return LOLR_Template;
2745
Richard Smithb8b41d32013-10-07 19:57:58 +00002746 if (FoundStringTemplate)
2747 return LOLR_StringTemplate;
2748
Richard Smithbcc22fc2012-03-09 08:00:36 +00002749 // Didn't find anything we could use.
2750 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2751 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002752 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2753 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002754 return LOLR_Error;
2755}
2756
John McCall8fe68082010-01-26 07:16:45 +00002757void ADLResult::insert(NamedDecl *New) {
2758 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2759
2760 // If we haven't yet seen a decl for this key, or the last decl
2761 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00002762 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00002763 Old = New;
2764 return;
2765 }
2766
2767 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002768 FunctionDecl *OldFD = Old->getAsFunction();
2769 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002770
2771 FunctionDecl *Cursor = NewFD;
2772 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002773 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002774
2775 // If we got to the end without finding OldFD, OldFD is the newer
2776 // declaration; leave things as they are.
2777 if (!Cursor) return;
2778
2779 // If we do find OldFD, then NewFD is newer.
2780 if (Cursor == OldFD) break;
2781
2782 // Otherwise, keep looking.
2783 }
2784
2785 Old = New;
2786}
2787
Richard Smith100b24a2014-04-17 01:52:14 +00002788void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2789 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002790 // Find all of the associated namespaces and classes based on the
2791 // arguments we have.
2792 AssociatedNamespaceSet AssociatedNamespaces;
2793 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002794 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002795 AssociatedNamespaces,
2796 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002797
2798 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002799 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2800 // and let Y be the lookup set produced by argument dependent
2801 // lookup (defined as follows). If X contains [...] then Y is
2802 // empty. Otherwise Y is the set of declarations found in the
2803 // namespaces associated with the argument types as described
2804 // below. The set of declarations found by the lookup of the name
2805 // is the union of X and Y.
2806 //
2807 // Here, we compute Y and add its members to the overloaded
2808 // candidate set.
2809 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002810 NSEnd = AssociatedNamespaces.end();
2811 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002812 // When considering an associated namespace, the lookup is the
2813 // same as the lookup performed when the associated namespace is
2814 // used as a qualifier (3.4.3.2) except that:
2815 //
2816 // -- Any using-directives in the associated namespace are
2817 // ignored.
2818 //
John McCallc7e8e792009-08-07 22:18:02 +00002819 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002820 // associated classes are visible within their respective
2821 // namespaces even if they are not visible during an ordinary
2822 // lookup (11.4).
David Blaikieff7d47a2012-12-19 00:45:41 +00002823 DeclContext::lookup_result R = (*NS)->lookup(Name);
2824 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2825 ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002826 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002827 // If the only declaration here is an ordinary friend, consider
2828 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002829 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2830 // If it's neither ordinarily visible nor a friend, we can't find it.
2831 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2832 continue;
2833
Richard Smith64017682013-07-17 23:53:16 +00002834 bool DeclaredInAssociatedClass = false;
2835 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2836 DeclContext *LexDC = DI->getLexicalDeclContext();
2837 if (isa<CXXRecordDecl>(LexDC) &&
2838 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2839 DeclaredInAssociatedClass = true;
2840 break;
2841 }
2842 }
2843 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002844 continue;
2845 }
Mike Stump11289f42009-09-09 15:08:12 +00002846
John McCall91f61fc2010-01-26 06:04:06 +00002847 if (isa<UsingShadowDecl>(D))
2848 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002849
Richard Smith100b24a2014-04-17 01:52:14 +00002850 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00002851 continue;
2852
2853 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002854 }
2855 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002856}
Douglas Gregor2d435302009-12-30 17:04:44 +00002857
2858//----------------------------------------------------------------------------
2859// Search for all visible declarations.
2860//----------------------------------------------------------------------------
2861VisibleDeclConsumer::~VisibleDeclConsumer() { }
2862
Richard Smithe156254d2013-08-20 20:35:18 +00002863bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2864
Douglas Gregor2d435302009-12-30 17:04:44 +00002865namespace {
2866
2867class ShadowContextRAII;
2868
2869class VisibleDeclsRecord {
2870public:
2871 /// \brief An entry in the shadow map, which is optimized to store a
2872 /// single declaration (the common case) but can also store a list
2873 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002874 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002875
2876private:
2877 /// \brief A mapping from declaration names to the declarations that have
2878 /// this name within a particular scope.
2879 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2880
2881 /// \brief A list of shadow maps, which is used to model name hiding.
2882 std::list<ShadowMap> ShadowMaps;
2883
2884 /// \brief The declaration contexts we have already visited.
2885 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2886
2887 friend class ShadowContextRAII;
2888
2889public:
2890 /// \brief Determine whether we have already visited this context
2891 /// (and, if not, note that we are going to visit that context now).
2892 bool visitedContext(DeclContext *Ctx) {
2893 return !VisitedContexts.insert(Ctx);
2894 }
2895
Douglas Gregor39982192010-08-15 06:18:01 +00002896 bool alreadyVisitedContext(DeclContext *Ctx) {
2897 return VisitedContexts.count(Ctx);
2898 }
2899
Douglas Gregor2d435302009-12-30 17:04:44 +00002900 /// \brief Determine whether the given declaration is hidden in the
2901 /// current scope.
2902 ///
2903 /// \returns the declaration that hides the given declaration, or
2904 /// NULL if no such declaration exists.
2905 NamedDecl *checkHidden(NamedDecl *ND);
2906
2907 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002908 void add(NamedDecl *ND) {
2909 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2910 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002911};
2912
2913/// \brief RAII object that records when we've entered a shadow context.
2914class ShadowContextRAII {
2915 VisibleDeclsRecord &Visible;
2916
2917 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2918
2919public:
2920 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2921 Visible.ShadowMaps.push_back(ShadowMap());
2922 }
2923
2924 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002925 Visible.ShadowMaps.pop_back();
2926 }
2927};
2928
2929} // end anonymous namespace
2930
Douglas Gregor2d435302009-12-30 17:04:44 +00002931NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002932 // Look through using declarations.
2933 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002934
Douglas Gregor2d435302009-12-30 17:04:44 +00002935 unsigned IDNS = ND->getIdentifierNamespace();
2936 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2937 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2938 SM != SMEnd; ++SM) {
2939 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2940 if (Pos == SM->end())
2941 continue;
2942
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002944 IEnd = Pos->second.end();
2945 I != IEnd; ++I) {
2946 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002947 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002949 Decl::IDNS_ObjCProtocol)))
2950 continue;
2951
2952 // Protocols are in distinct namespaces from everything else.
2953 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2954 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2955 (*I)->getIdentifierNamespace() != IDNS)
2956 continue;
2957
Douglas Gregor09bbc652010-01-14 15:47:35 +00002958 // Functions and function templates in the same scope overload
2959 // rather than hide. FIXME: Look for hiding based on function
2960 // signatures!
Alp Tokera2794f92014-01-22 07:29:52 +00002961 if ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
2962 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002963 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002964 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965
Douglas Gregor2d435302009-12-30 17:04:44 +00002966 // We've found a declaration that hides this one.
2967 return *I;
2968 }
2969 }
2970
Craig Topperc3ec1492014-05-26 06:22:03 +00002971 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00002972}
2973
2974static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2975 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002976 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002977 VisibleDeclConsumer &Consumer,
2978 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002979 if (!Ctx)
2980 return;
2981
Douglas Gregor2d435302009-12-30 17:04:44 +00002982 // Make sure we don't visit the same context twice.
2983 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2984 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002985
Douglas Gregor7454c562010-07-02 20:37:36 +00002986 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2987 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2988
Douglas Gregor2d435302009-12-30 17:04:44 +00002989 // Enumerate all of the results in this context.
Aaron Ballman576114e2014-03-14 15:28:49 +00002990 for (const auto &R : Ctx->lookups()) {
2991 for (auto *I : R) {
2992 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002993 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002994 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002995 Visited.add(ND);
2996 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002997 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002998 }
2999 }
3000
3001 // Traverse using directives for qualified name lookup.
3002 if (QualifiedNameLookup) {
3003 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003004 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003005 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003006 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003007 }
3008 }
3009
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003010 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003011 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003012 if (!Record->hasDefinition())
3013 return;
3014
Aaron Ballman574705e2014-03-13 15:41:46 +00003015 for (const auto &B : Record->bases()) {
3016 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017
Douglas Gregor2d435302009-12-30 17:04:44 +00003018 // Don't look into dependent bases, because name lookup can't look
3019 // there anyway.
3020 if (BaseType->isDependentType())
3021 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003022
Douglas Gregor2d435302009-12-30 17:04:44 +00003023 const RecordType *Record = BaseType->getAs<RecordType>();
3024 if (!Record)
3025 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003026
Douglas Gregor2d435302009-12-30 17:04:44 +00003027 // FIXME: It would be nice to be able to determine whether referencing
3028 // a particular member would be ambiguous. For example, given
3029 //
3030 // struct A { int member; };
3031 // struct B { int member; };
3032 // struct C : A, B { };
3033 //
3034 // void f(C *c) { c->### }
3035 //
3036 // accessing 'member' would result in an ambiguity. However, we
3037 // could be smart enough to qualify the member with the base
3038 // class, e.g.,
3039 //
3040 // c->B::member
3041 //
3042 // or
3043 //
3044 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003045
Douglas Gregor2d435302009-12-30 17:04:44 +00003046 // Find results in this base class (and its bases).
3047 ShadowContextRAII Shadow(Visited);
3048 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003049 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003050 }
3051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003053 // Traverse the contexts of Objective-C classes.
3054 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3055 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003056 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003057 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003058 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003059 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003060 }
3061
3062 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003063 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003064 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003065 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003066 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003067 }
3068
3069 // Traverse the superclass.
3070 if (IFace->getSuperClass()) {
3071 ShadowContextRAII Shadow(Visited);
3072 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003073 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003075
Douglas Gregor0b59e802010-04-19 18:02:19 +00003076 // If there is an implementation, traverse it. We do this to find
3077 // synthesized ivars.
3078 if (IFace->getImplementation()) {
3079 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003080 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003081 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003082 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003083 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003084 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003085 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003086 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003087 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003088 }
3089 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003090 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003091 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003092 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003093 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095
Douglas Gregor0b59e802010-04-19 18:02:19 +00003096 // If there is an implementation, traverse it.
3097 if (Category->getImplementation()) {
3098 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003099 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003100 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003102 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003103}
3104
3105static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3106 UnqualUsingDirectiveSet &UDirs,
3107 VisibleDeclConsumer &Consumer,
3108 VisibleDeclsRecord &Visited) {
3109 if (!S)
3110 return;
3111
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112 if (!S->getEntity() ||
3113 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003114 !Visited.alreadyVisitedContext(S->getEntity())) ||
3115 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003116 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003117 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003118 for (auto *D : S->decls()) {
3119 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003120 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003121 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003122 Visited.add(ND);
3123 }
3124 }
3125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003126
Douglas Gregor66230062010-03-15 14:33:29 +00003127 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003128 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003129 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003130 // Look into this scope's declaration context, along with any of its
3131 // parent lookup contexts (e.g., enclosing classes), up to the point
3132 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003133 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003134 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003135
Douglas Gregorea166062010-03-15 15:26:48 +00003136 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003137 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003138 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3139 if (Method->isInstanceMethod()) {
3140 // For instance methods, look for ivars in the method's interface.
3141 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3142 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003143 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003144 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003145 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003146 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003147 }
3148
3149 // We've already performed all of the name lookup that we need
3150 // to for Objective-C methods; the next context will be the
3151 // outer scope.
3152 break;
3153 }
3154
Douglas Gregor2d435302009-12-30 17:04:44 +00003155 if (Ctx->isFunctionOrMethod())
3156 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157
3158 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003159 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003160 }
3161 } else if (!S->getParent()) {
3162 // Look into the translation unit scope. We walk through the translation
3163 // unit's declaration context, because the Scope itself won't have all of
3164 // the declarations if we loaded a precompiled header.
3165 // FIXME: We would like the translation unit's Scope object to point to the
3166 // translation unit, so we don't need this special "if" branch. However,
3167 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003168 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003169 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003170 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003171 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003173 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003174 }
3175
Douglas Gregor2d435302009-12-30 17:04:44 +00003176 if (Entity) {
3177 // Lookup visible declarations in any namespaces found by using
3178 // directives.
3179 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003180 std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
Douglas Gregor2d435302009-12-30 17:04:44 +00003181 for (; UI != UEnd; ++UI)
3182 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003184 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003185 }
3186
3187 // Lookup names in the parent scope.
3188 ShadowContextRAII Shadow(Visited);
3189 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3190}
3191
3192void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003193 VisibleDeclConsumer &Consumer,
3194 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003195 // Determine the set of using directives available during
3196 // unqualified name lookup.
3197 Scope *Initial = S;
3198 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003199 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003200 // Find the first namespace or translation-unit scope.
3201 while (S && !isNamespaceOrTranslationUnitScope(S))
3202 S = S->getParent();
3203
3204 UDirs.visitScopeChain(Initial, S);
3205 }
3206 UDirs.done();
3207
3208 // Look for visible declarations.
3209 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003210 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003211 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003212 if (!IncludeGlobalScope)
3213 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003214 ShadowContextRAII Shadow(Visited);
3215 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3216}
3217
3218void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003219 VisibleDeclConsumer &Consumer,
3220 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003221 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003222 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003223 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003224 if (!IncludeGlobalScope)
3225 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003226 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003227 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003228 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003229}
3230
Chris Lattner43e7f312011-02-18 02:08:43 +00003231/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003232/// If GnuLabelLoc is a valid source location, then this is a definition
3233/// of an __label__ label name, otherwise it is a normal label definition
3234/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003235LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003236 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003237 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003238 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003239
3240 if (GnuLabelLoc.isValid()) {
3241 // Local label definitions always shadow existing labels.
3242 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3243 Scope *S = CurScope;
3244 PushOnScopeChains(Res, S, true);
3245 return cast<LabelDecl>(Res);
3246 }
3247
3248 // Not a GNU local label.
3249 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3250 // If we found a label, check to see if it is in the same context as us.
3251 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003252 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003253 Res = nullptr;
3254 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003255 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003256 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3257 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003258 assert(S && "Not in a function?");
3259 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003260 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003261 return cast<LabelDecl>(Res);
3262}
3263
3264//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003265// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003266//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003267
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003268static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3269 TypoCorrection &Candidate) {
3270 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3271 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3272}
3273
3274static void LookupPotentialTypoResult(Sema &SemaRef,
3275 LookupResult &Res,
3276 IdentifierInfo *Name,
3277 Scope *S, CXXScopeSpec *SS,
3278 DeclContext *MemberContext,
3279 bool EnteringContext,
3280 bool isObjCIvarLookup,
3281 bool FindHidden);
3282
3283// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3284// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3285// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3286static void getNestedNameSpecifierIdentifiers(
3287 NestedNameSpecifier *NNS,
3288 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3289 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3290 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3291 else
3292 Identifiers.clear();
3293
3294 const IdentifierInfo *II = nullptr;
3295
3296 switch (NNS->getKind()) {
3297 case NestedNameSpecifier::Identifier:
3298 II = NNS->getAsIdentifier();
3299 break;
3300
3301 case NestedNameSpecifier::Namespace:
3302 if (NNS->getAsNamespace()->isAnonymousNamespace())
3303 return;
3304 II = NNS->getAsNamespace()->getIdentifier();
3305 break;
3306
3307 case NestedNameSpecifier::NamespaceAlias:
3308 II = NNS->getAsNamespaceAlias()->getIdentifier();
3309 break;
3310
3311 case NestedNameSpecifier::TypeSpecWithTemplate:
3312 case NestedNameSpecifier::TypeSpec:
3313 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3314 break;
3315
3316 case NestedNameSpecifier::Global:
3317 return;
3318 }
3319
3320 if (II)
3321 Identifiers.push_back(II);
3322}
3323
Douglas Gregor2d435302009-12-30 17:04:44 +00003324namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003325
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003326class SpecifierInfo {
3327 public:
3328 DeclContext* DeclCtx;
3329 NestedNameSpecifier* NameSpecifier;
3330 unsigned EditDistance;
3331
3332 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3333 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3334};
3335
3336typedef SmallVector<DeclContext*, 4> DeclContextList;
3337typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3338
3339class NamespaceSpecifierSet {
3340 ASTContext &Context;
3341 DeclContextList CurContextChain;
3342 std::string CurNameSpecifier;
3343 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3344 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
3345 bool isSorted;
3346
3347 SpecifierInfoList Specifiers;
3348 llvm::SmallSetVector<unsigned, 4> Distances;
3349 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3350
3351 /// \brief Helper for building the list of DeclContexts between the current
3352 /// context and the top of the translation unit
3353 static DeclContextList buildContextChain(DeclContext *Start);
3354
3355 void sortNamespaces();
3356
3357 public:
3358 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3359 CXXScopeSpec *CurScopeSpec)
3360 : Context(Context), CurContextChain(buildContextChain(CurContext)),
3361 isSorted(false) {
3362 if (NestedNameSpecifier *NNS =
3363 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3364 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3365 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3366
3367 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3368 }
3369 // Build the list of identifiers that would be used for an absolute
3370 // (from the global context) NestedNameSpecifier referring to the current
3371 // context.
3372 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3373 CEnd = CurContextChain.rend();
3374 C != CEnd; ++C) {
3375 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3376 CurContextIdentifiers.push_back(ND->getIdentifier());
3377 }
3378
3379 // Add the global context as a NestedNameSpecifier
3380 Distances.insert(1);
3381 DistanceMap[1].push_back(
3382 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3383 NestedNameSpecifier::GlobalSpecifier(Context), 1));
3384 }
3385
3386 /// \brief Add the DeclContext (a namespace or record) to the set, computing
3387 /// the corresponding NestedNameSpecifier and its distance in the process.
3388 void addNameSpecifier(DeclContext *Ctx);
3389
3390 typedef SpecifierInfoList::iterator iterator;
3391 iterator begin() {
3392 if (!isSorted) sortNamespaces();
3393 return Specifiers.begin();
3394 }
3395 iterator end() { return Specifiers.end(); }
3396};
3397
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003398typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003399typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003400typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003401
3402static const unsigned MaxTypoDistanceResultSets = 5;
3403
Douglas Gregor2d435302009-12-30 17:04:44 +00003404class TypoCorrectionConsumer : public VisibleDeclConsumer {
3405 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003406 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003407
3408 /// \brief The results found that have the smallest edit distance
3409 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003410 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003411 /// The pointer value being set to the current DeclContext indicates
3412 /// whether there is a keyword with this name.
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003413 TypoEditDistanceMap CorrectionResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003414
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003415 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003416
Douglas Gregor2d435302009-12-30 17:04:44 +00003417public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003418 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419 : Typo(Typo->getName()),
Richard Smithe156254d2013-08-20 20:35:18 +00003420 SemaRef(SemaRef) {}
3421
Craig Toppere14c0f82014-03-12 04:55:44 +00003422 bool includeHiddenDecls() const override { return true; }
Douglas Gregor2d435302009-12-30 17:04:44 +00003423
Craig Toppere14c0f82014-03-12 04:55:44 +00003424 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3425 bool InBaseClass) override;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003426 void FoundName(StringRef Name);
3427 void addKeywordResult(StringRef Keyword);
Craig Topperc3ec1492014-05-26 06:22:03 +00003428 void addName(StringRef Name, NamedDecl *ND,
3429 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003430 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003431
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003432 typedef TypoResultsMap::iterator result_iterator;
3433 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003434 distance_iterator begin() { return CorrectionResults.begin(); }
3435 distance_iterator end() { return CorrectionResults.end(); }
3436 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3437 unsigned size() const { return CorrectionResults.size(); }
3438 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003439
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003440 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003441 return CorrectionResults.begin()->second[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003442 }
3443
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003444 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003445 if (CorrectionResults.empty())
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003446 return (std::numeric_limits<unsigned>::max)();
3447
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003448 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003449 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003450 }
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003451
3452 TypoResultsMap &getBestResults() {
3453 return CorrectionResults.begin()->second;
3454 }
3455
Douglas Gregor2d435302009-12-30 17:04:44 +00003456};
3457
3458}
3459
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003461 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003462 // Don't consider hidden names for typo correction.
3463 if (Hiding)
3464 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465
Douglas Gregor2d435302009-12-30 17:04:44 +00003466 // Only consider entities with identifiers for names, ignoring
3467 // special names (constructors, overloaded operators, selectors,
3468 // etc.).
3469 IdentifierInfo *Name = ND->getIdentifier();
3470 if (!Name)
3471 return;
3472
Richard Smithe156254d2013-08-20 20:35:18 +00003473 // Only consider visible declarations and declarations from modules with
3474 // names that exactly match.
3475 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3476 !findAcceptableDecl(SemaRef, ND))
3477 return;
3478
Douglas Gregor57756ea2010-10-14 22:11:03 +00003479 FoundName(Name->getName());
3480}
3481
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003482void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003483 // Compute the edit distance between the typo and the name of this
3484 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003485 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003486}
3487
3488void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3489 // Compute the edit distance between the typo and this keyword,
3490 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003491 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003492}
3493
3494void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3495 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003496 // Use a simple length-based heuristic to determine the minimum possible
3497 // edit distance. If the minimum isn't good enough, bail out early.
3498 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003499 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003500 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003502 // Compute an upper bound on the allowable edit distance, so that the
3503 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003504 unsigned UpperBound = (Typo.size() + 2) / 3 + 1;
3505 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3506 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003508 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003509 if (isKeyword) TC.makeKeyword();
3510 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003511}
3512
3513void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003514 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003515 TypoResultList &CList =
3516 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003517
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003518 if (!CList.empty() && !CList.back().isResolved())
3519 CList.pop_back();
3520 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3521 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3522 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3523 RI != RIEnd; ++RI) {
3524 // If the Correction refers to a decl already in the result list,
3525 // replace the existing result if the string representation of Correction
3526 // comes before the current result alphabetically, then stop as there is
3527 // nothing more to be done to add Correction to the candidate set.
3528 if (RI->getCorrectionDecl() == NewND) {
3529 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3530 *RI = Correction;
3531 return;
3532 }
3533 }
3534 }
3535 if (CList.empty() || Correction.isResolved())
3536 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003537
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003538 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Benjamin Kramer167e9992014-03-02 12:20:24 +00003539 erase(std::prev(CorrectionResults.end()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003540}
3541
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003542DeclContextList NamespaceSpecifierSet::buildContextChain(DeclContext *Start) {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003543 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003544 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00003545 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003546 DC = DC->getLookupParent()) {
3547 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3548 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3549 !(ND && ND->isAnonymousNamespace()))
3550 Chain.push_back(DC->getPrimaryContext());
3551 }
3552 return Chain;
3553}
3554
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003555void NamespaceSpecifierSet::sortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003556 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003557 sortedDistances.append(Distances.begin(), Distances.end());
3558
3559 if (sortedDistances.size() > 1)
3560 std::sort(sortedDistances.begin(), sortedDistances.end());
3561
3562 Specifiers.clear();
Craig Topper2341c0d2013-07-04 03:08:24 +00003563 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3564 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003565 DI != DIEnd; ++DI) {
3566 SpecifierInfoList &SpecList = DistanceMap[*DI];
3567 Specifiers.append(SpecList.begin(), SpecList.end());
3568 }
3569
3570 isSorted = true;
3571}
3572
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003573static unsigned BuildNestedNameSpecifier(ASTContext &Context,
3574 DeclContextList &DeclChain,
3575 NestedNameSpecifier *&NNS) {
3576 unsigned NumSpecifiers = 0;
3577 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3578 CEnd = DeclChain.rend();
3579 C != CEnd; ++C) {
3580 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3581 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3582 ++NumSpecifiers;
3583 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3584 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3585 RD->getTypeForDecl());
3586 ++NumSpecifiers;
3587 }
3588 }
3589 return NumSpecifiers;
3590}
3591
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003592void NamespaceSpecifierSet::addNameSpecifier(DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003593 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003594 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003595 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003596 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3597
3598 // Eliminate common elements from the two DeclContext chains.
3599 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3600 CEnd = CurContextChain.rend();
3601 C != CEnd && !NamespaceDeclChain.empty() &&
3602 NamespaceDeclChain.back() == *C; ++C) {
3603 NamespaceDeclChain.pop_back();
3604 }
3605
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003606 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3607 NumSpecifiers = BuildNestedNameSpecifier(Context, NamespaceDeclChain, NNS);
3608
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003609 // Add an explicit leading '::' specifier if needed.
3610 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003611 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003612 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003613 NumSpecifiers =
3614 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003615 } else if (NamedDecl *ND =
3616 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003617 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003618 bool SameNameSpecifier = false;
3619 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003620 CurNameSpecifierIdentifiers.end(),
3621 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003622 std::string NewNameSpecifier;
3623 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3624 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3625 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3626 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3627 SpecifierOStream.flush();
3628 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003629 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003630 if (SameNameSpecifier ||
3631 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3632 Name) != CurContextIdentifiers.end()) {
3633 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3634 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3635 NumSpecifiers =
3636 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003637 }
3638 }
3639
3640 // If the built NestedNameSpecifier would be replacing an existing
3641 // NestedNameSpecifier, use the number of component identifiers that
3642 // would need to be changed as the edit distance instead of the number
3643 // of components in the built NestedNameSpecifier.
3644 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3645 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3646 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3647 NumSpecifiers = llvm::ComputeEditDistance(
3648 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3649 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3650 }
3651
3652 isSorted = false;
3653 Distances.insert(NumSpecifiers);
3654 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3655}
3656
Douglas Gregord507d772010-10-20 03:06:34 +00003657/// \brief Perform name lookup for a possible result for typo correction.
3658static void LookupPotentialTypoResult(Sema &SemaRef,
3659 LookupResult &Res,
3660 IdentifierInfo *Name,
3661 Scope *S, CXXScopeSpec *SS,
3662 DeclContext *MemberContext,
3663 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003664 bool isObjCIvarLookup,
3665 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003666 Res.suppressDiagnostics();
3667 Res.clear();
3668 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003669 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003671 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003672 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003673 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3674 Res.addDecl(Ivar);
3675 Res.resolveKind();
3676 return;
3677 }
3678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003679
Douglas Gregord507d772010-10-20 03:06:34 +00003680 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3681 Res.addDecl(Prop);
3682 Res.resolveKind();
3683 return;
3684 }
3685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003686
Douglas Gregord507d772010-10-20 03:06:34 +00003687 SemaRef.LookupQualifiedName(Res, MemberContext);
3688 return;
3689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003690
3691 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003692 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003693
Douglas Gregord507d772010-10-20 03:06:34 +00003694 // Fake ivar lookup; this should really be part of
3695 // LookupParsedName.
3696 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3697 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003699 (Res.isSingleResult() &&
3700 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003702 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3703 Res.addDecl(IV);
3704 Res.resolveKind();
3705 }
3706 }
3707 }
3708}
3709
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003710/// \brief Add keywords to the consumer as possible typo corrections.
3711static void AddKeywordsToConsumer(Sema &SemaRef,
3712 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003713 Scope *S, CorrectionCandidateCallback &CCC,
3714 bool AfterNestedNameSpecifier) {
3715 if (AfterNestedNameSpecifier) {
3716 // For 'X::', we know exactly which keywords can appear next.
3717 Consumer.addKeywordResult("template");
3718 if (CCC.WantExpressionKeywords)
3719 Consumer.addKeywordResult("operator");
3720 return;
3721 }
3722
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003723 if (CCC.WantObjCSuper)
3724 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003725
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003726 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003727 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003728 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003729 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003730 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003731 "_Complex", "_Imaginary",
3732 // storage-specifiers as well
3733 "extern", "inline", "static", "typedef"
3734 };
3735
Craig Toppere5ce8312013-07-15 03:38:40 +00003736 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003737 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3738 Consumer.addKeywordResult(CTypeSpecs[I]);
3739
David Blaikiebbafb8a2012-03-11 07:00:24 +00003740 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003741 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003742 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003743 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003744 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003745 Consumer.addKeywordResult("_Bool");
3746
David Blaikiebbafb8a2012-03-11 07:00:24 +00003747 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003748 Consumer.addKeywordResult("class");
3749 Consumer.addKeywordResult("typename");
3750 Consumer.addKeywordResult("wchar_t");
3751
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003752 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003753 Consumer.addKeywordResult("char16_t");
3754 Consumer.addKeywordResult("char32_t");
3755 Consumer.addKeywordResult("constexpr");
3756 Consumer.addKeywordResult("decltype");
3757 Consumer.addKeywordResult("thread_local");
3758 }
3759 }
3760
David Blaikiebbafb8a2012-03-11 07:00:24 +00003761 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003762 Consumer.addKeywordResult("typeof");
3763 }
3764
David Blaikiebbafb8a2012-03-11 07:00:24 +00003765 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003766 Consumer.addKeywordResult("const_cast");
3767 Consumer.addKeywordResult("dynamic_cast");
3768 Consumer.addKeywordResult("reinterpret_cast");
3769 Consumer.addKeywordResult("static_cast");
3770 }
3771
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003772 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003773 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003774 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003775 Consumer.addKeywordResult("false");
3776 Consumer.addKeywordResult("true");
3777 }
3778
David Blaikiebbafb8a2012-03-11 07:00:24 +00003779 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003780 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003781 "delete", "new", "operator", "throw", "typeid"
3782 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003783 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003784 for (unsigned I = 0; I != NumCXXExprs; ++I)
3785 Consumer.addKeywordResult(CXXExprs[I]);
3786
3787 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3788 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3789 Consumer.addKeywordResult("this");
3790
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003791 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003792 Consumer.addKeywordResult("alignof");
3793 Consumer.addKeywordResult("nullptr");
3794 }
3795 }
Jordan Rose58d54722012-06-30 21:33:57 +00003796
3797 if (SemaRef.getLangOpts().C11) {
3798 // FIXME: We should not suggest _Alignof if the alignof macro
3799 // is present.
3800 Consumer.addKeywordResult("_Alignof");
3801 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003802 }
3803
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003804 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003805 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3806 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003807 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003808 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00003809 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003810 for (unsigned I = 0; I != NumCStmts; ++I)
3811 Consumer.addKeywordResult(CStmts[I]);
3812
David Blaikiebbafb8a2012-03-11 07:00:24 +00003813 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003814 Consumer.addKeywordResult("catch");
3815 Consumer.addKeywordResult("try");
3816 }
3817
3818 if (S && S->getBreakParent())
3819 Consumer.addKeywordResult("break");
3820
3821 if (S && S->getContinueParent())
3822 Consumer.addKeywordResult("continue");
3823
3824 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3825 Consumer.addKeywordResult("case");
3826 Consumer.addKeywordResult("default");
3827 }
3828 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003829 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003830 Consumer.addKeywordResult("namespace");
3831 Consumer.addKeywordResult("template");
3832 }
3833
3834 if (S && S->isClassScope()) {
3835 Consumer.addKeywordResult("explicit");
3836 Consumer.addKeywordResult("friend");
3837 Consumer.addKeywordResult("mutable");
3838 Consumer.addKeywordResult("private");
3839 Consumer.addKeywordResult("protected");
3840 Consumer.addKeywordResult("public");
3841 Consumer.addKeywordResult("virtual");
3842 }
3843 }
3844
David Blaikiebbafb8a2012-03-11 07:00:24 +00003845 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003846 Consumer.addKeywordResult("using");
3847
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003848 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003849 Consumer.addKeywordResult("static_assert");
3850 }
3851 }
3852}
3853
Richard Smithe156254d2013-08-20 20:35:18 +00003854/// \brief Check whether the declarations found for a typo correction are
3855/// visible, and if none of them are, convert the correction to an 'import
3856/// a module' correction.
3857static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3858 DeclarationName TypoName) {
3859 if (TC.begin() == TC.end())
3860 return;
3861
3862 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3863
3864 for (/**/; DI != DE; ++DI)
3865 if (!LookupResult::isVisible(SemaRef, *DI))
3866 break;
3867 // Nothing to do if all decls are visible.
3868 if (DI == DE)
3869 return;
3870
3871 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3872 bool AnyVisibleDecls = !NewDecls.empty();
3873
3874 for (/**/; DI != DE; ++DI) {
3875 NamedDecl *VisibleDecl = *DI;
3876 if (!LookupResult::isVisible(SemaRef, *DI))
3877 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3878
3879 if (VisibleDecl) {
3880 if (!AnyVisibleDecls) {
3881 // Found a visible decl, discard all hidden ones.
3882 AnyVisibleDecls = true;
3883 NewDecls.clear();
3884 }
3885 NewDecls.push_back(VisibleDecl);
3886 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3887 NewDecls.push_back(*DI);
3888 }
3889
3890 if (NewDecls.empty())
3891 TC = TypoCorrection();
3892 else {
3893 TC.setCorrectionDecls(NewDecls);
3894 TC.setRequiresImport(!AnyVisibleDecls);
3895 }
3896}
3897
Douglas Gregor2d435302009-12-30 17:04:44 +00003898/// \brief Try to "correct" a typo in the source code by finding
3899/// visible declarations whose names are similar to the name that was
3900/// present in the source code.
3901///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003902/// \param TypoName the \c DeclarationNameInfo structure that contains
3903/// the name that was present in the source code along with its location.
3904///
3905/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003906///
3907/// \param S the scope in which name lookup occurs.
3908///
3909/// \param SS the nested-name-specifier that precedes the name we're
3910/// looking for, if present.
3911///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003912/// \param CCC A CorrectionCandidateCallback object that provides further
3913/// validation of typo correction candidates. It also provides flags for
3914/// determining the set of keywords permitted.
3915///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003916/// \param MemberContext if non-NULL, the context in which to look for
3917/// a member access expression.
3918///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003920/// the nested-name-specifier SS.
3921///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003922/// \param OPT when non-NULL, the search for visible declarations will
3923/// also walk the protocols in the qualified interfaces of \p OPT.
3924///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003925/// \returns a \c TypoCorrection containing the corrected name if the typo
3926/// along with information such as the \c NamedDecl where the corrected name
3927/// was declared, and any additional \c NestedNameSpecifier needed to access
3928/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3929TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3930 Sema::LookupNameKind LookupKind,
3931 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003932 CorrectionCandidateCallback &CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00003933 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003934 DeclContext *MemberContext,
3935 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00003936 const ObjCObjectPointerType *OPT,
3937 bool RecordFailure) {
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00003938 // Always let the ExternalSource have the first chance at correction, even
3939 // if we would otherwise have given up.
3940 if (ExternalSource) {
3941 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
3942 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
3943 return Correction;
3944 }
3945
Richard Smith1fff95c2013-09-12 23:28:08 +00003946 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
3947 DisableTypoCorrection)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003948 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003949
Francois Pichet9c391132011-12-03 15:55:29 +00003950 // In Microsoft mode, don't perform typo correction in a template member
3951 // function dependent context because it interferes with the "lookup into
3952 // dependent bases of class templates" feature.
Alp Tokerbfa39342014-01-14 12:51:41 +00003953 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00003954 isa<CXXMethodDecl>(CurContext))
3955 return TypoCorrection();
3956
Douglas Gregor2d435302009-12-30 17:04:44 +00003957 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003958 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003959 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003960 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003961
3962 // If the scope specifier itself was invalid, don't try to correct
3963 // typos.
3964 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003965 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003966
3967 // Never try to correct typos during template deduction or
3968 // instantiation.
3969 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003970 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00003972 // Don't try to correct 'super'.
3973 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3974 return TypoCorrection();
3975
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00003976 // Abort if typo correction already failed for this specific typo.
3977 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
3978 if (locs != TypoCorrectionFailures.end() &&
Aaron Ballman7fc6e1b2013-10-05 19:56:07 +00003979 locs->second.count(TypoName.getLoc()))
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00003980 return TypoCorrection();
3981
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003982 // Don't try to correct the identifier "vector" when in AltiVec mode.
3983 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
3984 // remove this workaround.
3985 if (getLangOpts().AltiVec && Typo->isStr("vector"))
3986 return TypoCorrection();
3987
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003988 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989
John Thompson2309b152014-05-07 22:47:08 +00003990 // If we're handling a missing symbol error, using modules, and the
3991 // special search all modules option is used, look for a missing import.
John Thompson2d94bbb2014-04-23 19:04:32 +00003992 if ((Mode == CTK_ErrorRecovery) && getLangOpts().Modules &&
3993 getLangOpts().ModulesSearchAll) {
John Thompson2309b152014-05-07 22:47:08 +00003994 // The following has the side effect of loading the missing module.
3995 getModuleLoader().lookupMissingImports(Typo->getName(),
3996 TypoName.getLocStart());
John Thompson2255f2c2014-04-23 12:57:01 +00003997 }
3998
3999 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
4000
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004001 // If a callback object considers an empty typo correction candidate to be
4002 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004003 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004004 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004005
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004006 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00004007 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004008 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004009 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004010 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004011
4012 // Look in qualified interfaces.
4013 if (OPT) {
Aaron Ballman83731462014-03-17 16:14:00 +00004014 for (auto *I : OPT->quals())
4015 LookupVisibleDecls(I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004016 }
4017 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004018 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4019 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004020 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004021
Douglas Gregor87074f12010-10-20 01:32:02 +00004022 // Provide a stop gap for files that are just seriously broken. Trying
4023 // to correct all typos can turn into a HUGE performance penalty, causing
4024 // some files to take minutes to get rejected by the parser.
4025 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004026 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00004027 ++TyposCorrected;
4028
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004029 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00004030 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00004031 IsUnqualifiedLookup = true;
4032 UnqualifiedTyposCorrectedMap::iterator Cached
4033 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004034 if (Cached != UnqualifiedTyposCorrected.end()) {
4035 // Add the cached value, unless it's a keyword or fails validation. In the
4036 // keyword case, we'll end up adding the keyword below.
4037 if (Cached->second) {
4038 if (!Cached->second.isKeyword() &&
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004039 isCandidateViable(CCC, Cached->second)) {
4040 // Do not use correction that is unaccessible in the given scope.
Serge Pavlove8ae13f2013-10-15 14:24:32 +00004041 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004042 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4043 CorrectionDecl->getLocation());
4044 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4045 if (LookupName(R, S))
4046 Consumer.addCorrection(Cached->second);
4047 }
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004048 } else {
4049 // Only honor no-correction cache hits when a callback that will validate
4050 // correction candidates is not being used.
4051 if (!ValidatingCallback)
4052 return TypoCorrection();
4053 }
4054 }
4055 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00004056 // Provide a stop gap for files that are just seriously broken. Trying
4057 // to correct all typos can turn into a HUGE performance penalty, causing
4058 // some files to take minutes to get rejected by the parser.
4059 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004060 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004061 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004063
Douglas Gregorb11f9452012-03-26 16:54:18 +00004064 // Determine whether we are going to search in the various namespaces for
4065 // corrections.
4066 bool SearchNamespaces
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004067 = getLangOpts().CPlusPlus &&
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004068 (IsUnqualifiedLookup || (SS && SS->isSet()));
Richard Smithe156254d2013-08-20 20:35:18 +00004069 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004070 // adding or changing the nested name specifier.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004071 unsigned TypoLen = Typo->getName().size();
4072 bool AllowOnlyNNSChanges = TypoLen < 3;
4073
Douglas Gregorb11f9452012-03-26 16:54:18 +00004074 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004075 // For unqualified lookup, look through all of the names that we have
4076 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004077 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004078 for (IdentifierTable::iterator I = Context.Idents.begin(),
4079 IEnd = Context.Idents.end();
4080 I != IEnd; ++I)
4081 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004082
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004083 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004084 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004085 if (IdentifierInfoLookup *External
4086 = Context.Idents.getExternalIdentifierLookup()) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00004087 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004088 do {
4089 StringRef Name = Iter->Next();
4090 if (Name.empty())
4091 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00004092
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004093 Consumer.FoundName(Name);
4094 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00004095 }
Douglas Gregor2d435302009-12-30 17:04:44 +00004096 }
4097
Richard Smithb3a1df02012-06-08 21:35:42 +00004098 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004099
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004100 // If we haven't found anything, we're done.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004101 if (Consumer.empty())
4102 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4103 IsUnqualifiedLookup);
Douglas Gregor2d435302009-12-30 17:04:44 +00004104
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004105 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4106 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004107 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004108 if (ED > 0 && TypoLen / ED < 3)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004109 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4110 IsUnqualifiedLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004111
Douglas Gregorb11f9452012-03-26 16:54:18 +00004112 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4113 // to search those namespaces.
4114 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004115 // Load any externally-known namespaces.
4116 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004117 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004118 LoadedExternalKnownNamespaces = true;
4119 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4120 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4121 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4122 }
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004123
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004124 for (auto KNPair : KnownNamespaces)
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004125 Namespaces.addNameSpecifier(KNPair.first);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004126
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004127 bool SSIsTemplate = false;
4128 if (NestedNameSpecifier *NNS =
Craig Topperc3ec1492014-05-26 06:22:03 +00004129 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004130 if (const Type *T = NNS->getAsType())
4131 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4132 }
Aaron Ballmane42430e2014-03-14 21:11:14 +00004133 for (const auto *TI : Context.types()) {
4134 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004135 CD = CD->getCanonicalDecl();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004136 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
Kaelyn Uhrain21a66172014-02-05 18:57:51 +00004137 !CD->isUnion() && CD->getIdentifier() &&
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004138 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004139 (CD->isBeingDefined() || CD->isCompleteDefinition()))
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004140 Namespaces.addNameSpecifier(CD);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004141 }
4142 }
Douglas Gregor87074f12010-10-20 01:32:02 +00004143 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004144
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004145 // Weed out any names that could not be found by name lookup or, if a
4146 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004147 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004148 LookupResult TmpRes(*this, TypoName, LookupKind);
4149 TmpRes.suppressDiagnostics();
4150 while (!Consumer.empty()) {
4151 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Benjamin Kramer73faad62012-04-14 08:26:28 +00004152 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4153 IEnd = DI->second.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004154 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004155 // If we only want nested name specifier corrections, ignore potential
Kaelyn Uhrainec262992014-03-21 21:54:25 +00004156 // corrections that have a different base identifier from the typo or
4157 // which have a normalized edit distance longer than the typo itself.
4158 if (AllowOnlyNNSChanges) {
4159 TypoCorrection &TC = I->second.front();
4160 if (TC.getCorrectionAsIdentifierInfo() != Typo ||
4161 TC.getEditDistance(true) > TypoLen) {
4162 TypoCorrectionConsumer::result_iterator Prev = I;
4163 ++I;
4164 DI->second.erase(Prev);
4165 continue;
4166 }
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004167 }
4168
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004169 // If the item already has been looked up or is a keyword, keep it.
4170 // If a validator callback object was given, drop the correction
4171 // unless it passes validation.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004172 bool Viable = false;
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004173 for (TypoResultList::iterator RI = I->second.begin();
4174 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004175 TypoResultList::iterator Prev = RI;
4176 ++RI;
4177 if (Prev->isResolved()) {
4178 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004179 RI = I->second.erase(Prev);
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004180 else
4181 Viable = true;
4182 }
4183 }
4184 if (Viable || I->second.empty()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004185 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004186 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004187 if (!Viable)
Benjamin Kramer73faad62012-04-14 08:26:28 +00004188 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004189 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004190 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004191 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004193 // Perform name lookup on this name.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004194 TypoCorrection &Candidate = I->second.front();
4195 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004196 DeclContext *TempMemberContext = MemberContext;
4197 CXXScopeSpec *TempSS = SS;
4198retry_lookup:
4199 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4200 TempMemberContext, EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004201 CCC.IsObjCIvarLookup,
4202 Name == TypoName.getName() &&
4203 !Candidate.WillReplaceSpecifier());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004204
4205 switch (TmpRes.getResultKind()) {
4206 case LookupResult::NotFound:
4207 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004208 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004209 if (TempSS) {
4210 // Immediately retry the lookup without the given CXXScopeSpec
Craig Topperc3ec1492014-05-26 06:22:03 +00004211 TempSS = nullptr;
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004212 Candidate.WillReplaceSpecifier(true);
4213 goto retry_lookup;
4214 }
4215 if (TempMemberContext) {
4216 if (SS && !TempSS)
4217 TempSS = SS;
Craig Topperc3ec1492014-05-26 06:22:03 +00004218 TempMemberContext = nullptr;
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004219 goto retry_lookup;
4220 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004221 QualifiedResults.push_back(Candidate);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004222 // We didn't find this name in our scope, or didn't like what we found;
4223 // ignore it.
4224 {
4225 TypoCorrectionConsumer::result_iterator Next = I;
4226 ++Next;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004227 DI->second.erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004228 I = Next;
4229 }
4230 break;
4231
4232 case LookupResult::Ambiguous:
4233 // We don't deal with ambiguities.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004234 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004235
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004236 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004237 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004238 // Store all of the Decls for overloaded symbols
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004239 for (auto *TRD : TmpRes)
4240 Candidate.addCorrectionDecl(TRD);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004241 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004242 if (!isCandidateViable(CCC, Candidate)) {
4243 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004244 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004245 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004246 break;
4247 }
4248
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004249 case LookupResult::Found: {
4250 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004251 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004252 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004253 if (!isCandidateViable(CCC, Candidate)) {
4254 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004255 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004256 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004257 break;
4258 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004259
4260 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
Benjamin Kramer73faad62012-04-14 08:26:28 +00004263 if (DI->second.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004264 Consumer.erase(DI);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004265 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004266 // If there are results in the closest possible bucket, stop
4267 break;
4268
4269 // Only perform the qualified lookups for C++
Douglas Gregorb11f9452012-03-26 16:54:18 +00004270 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004271 TmpRes.suppressDiagnostics();
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004272 for (auto QR : QualifiedResults) {
4273 for (auto NSI : Namespaces) {
4274 DeclContext *Ctx = NSI.DeclCtx;
4275 const Type *NSType = NSI.NameSpecifier->getAsType();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004276
4277 // If the current NestedNameSpecifier refers to a class and the
4278 // current correction candidate is the name of that class, then skip
4279 // it as it is unlikely a qualified version of the class' constructor
4280 // is an appropriate correction.
4281 if (CXXRecordDecl *NSDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004282 NSType ? NSType->getAsCXXRecordDecl() : nullptr) {
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004283 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004284 continue;
4285 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004286
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004287 TypoCorrection TC(QR);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004288 TC.ClearCorrectionDecls();
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004289 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4290 TC.setQualifierDistance(NSI.EditDistance);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004291 TC.setCallbackDistance(0); // Reset the callback distance
4292
4293 // If the current correction candidate and namespace combination are
4294 // too far away from the original typo based on the normalized edit
4295 // distance, then skip performing a qualified name lookup.
4296 unsigned TmpED = TC.getEditDistance(true);
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004297 if (QR.getCorrectionAsIdentifierInfo() != Typo &&
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004298 TmpED && TypoLen / TmpED < 3)
4299 continue;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004300
4301 TmpRes.clear();
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004302 TmpRes.setLookupName(QR.getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004303 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4304
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004305 // Any corrections added below will be validated in subsequent
4306 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004307 switch (TmpRes.getResultKind()) {
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004308 case LookupResult::Found:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004309 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004310 if (SS && SS->isValid()) {
4311 std::string NewQualified = TC.getAsString(getLangOpts());
4312 std::string OldQualified;
4313 llvm::raw_string_ostream OldOStream(OldQualified);
4314 SS->getScopeRep()->print(OldOStream, getPrintingPolicy());
4315 OldOStream << TypoName;
4316 // If correction candidate would be an identical written qualified
4317 // identifer, then the existing CXXScopeSpec probably included a
4318 // typedef that didn't get accounted for properly.
4319 if (OldOStream.str() == NewQualified)
4320 break;
4321 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004322 for (LookupResult::iterator TRD = TmpRes.begin(),
4323 TRDEnd = TmpRes.end();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004324 TRD != TRDEnd; ++TRD) {
4325 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004326 NSType ? NSType->getAsCXXRecordDecl()
4327 : nullptr,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00004328 TRD.getPair()) == AR_accessible)
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004329 TC.addCorrectionDecl(*TRD);
4330 }
4331 if (TC.isResolved())
4332 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004333 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004334 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004335 case LookupResult::NotFound:
4336 case LookupResult::NotFoundInCurrentInstantiation:
4337 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004338 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004339 break;
4340 }
4341 }
4342 }
4343 }
4344
4345 QualifiedResults.clear();
4346 }
4347
4348 // No corrections remain...
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004349 if (Consumer.empty())
4350 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004351
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004352 TypoResultsMap &BestResults = Consumer.getBestResults();
4353 ED = Consumer.getBestEditDistance(true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004354
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004355 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004356 // If this was an unqualified lookup and we believe the callback
4357 // object wouldn't have filtered out possible corrections, note
4358 // that no correction was found.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004359 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4360 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004361 }
4362
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004363 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004364 if (BestResults.size() == 1) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004365 const TypoResultList &CorrectionList = BestResults.begin()->second;
4366 const TypoCorrection &Result = CorrectionList.front();
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004367 if (CorrectionList.size() != 1)
4368 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004370 // Don't correct to a keyword that's the same as the typo; the keyword
4371 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004372 if (ED == 0 && Result.isKeyword())
4373 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004374
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004375 // Record the correction for unqualified lookup.
4376 if (IsUnqualifiedLookup)
4377 UnqualifiedTyposCorrected[Typo] = Result;
4378
David Blaikie04ea41c2012-10-12 20:00:44 +00004379 TypoCorrection TC = Result;
4380 TC.setCorrectionRange(SS, TypoName);
Richard Smithe156254d2013-08-20 20:35:18 +00004381 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie04ea41c2012-10-12 20:00:44 +00004382 return TC;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004383 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004384 else if (BestResults.size() > 1
4385 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4386 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4387 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4388 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004389 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004390 && BestResults["super"].front().isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004391 // Prefer 'super' when we're completing in a message-receiver
4392 // context.
4393
4394 // Don't correct to a keyword that's the same as the typo; the keyword
4395 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004396 if (ED == 0)
4397 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398
Douglas Gregor87074f12010-10-20 01:32:02 +00004399 // Record the correction for unqualified lookup.
4400 if (IsUnqualifiedLookup)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004401 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402
David Blaikie04ea41c2012-10-12 20:00:44 +00004403 TypoCorrection TC = BestResults["super"].front();
4404 TC.setCorrectionRange(SS, TypoName);
4405 return TC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004407
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004408 // Record the failure's location if needed and return an empty correction. If
4409 // this was an unqualified lookup and we believe the callback object did not
4410 // filter out possible corrections, also cache the failure for the typo.
4411 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4412 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004413}
4414
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004415void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4416 if (!CDecl) return;
4417
4418 if (isKeyword())
4419 CorrectionDecls.clear();
4420
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004421 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004422
4423 if (!CorrectionName)
4424 CorrectionName = CDecl->getDeclName();
4425}
4426
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004427std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4428 if (CorrectionNameSpec) {
4429 std::string tmpBuffer;
4430 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4431 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004432 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004433 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004434 }
4435
4436 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004437}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004438
4439bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4440 if (!candidate.isResolved())
4441 return true;
4442
4443 if (candidate.isKeyword())
4444 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4445 WantRemainingKeywords || WantObjCSuper;
4446
4447 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4448 CDeclEnd = candidate.end();
4449 CDecl != CDeclEnd; ++CDecl) {
4450 if (!isa<TypeDecl>(*CDecl))
4451 return true;
4452 }
4453
4454 return WantTypeSpecifiers;
4455}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004456
4457FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004458 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004459 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004460 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004461 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004462 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4463 WantRemainingKeywords = false;
4464}
4465
4466bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4467 if (!candidate.getCorrectionDecl())
4468 return candidate.isKeyword();
4469
4470 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4471 DIEnd = candidate.end();
4472 DI != DIEnd; ++DI) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004473 FunctionDecl *FD = nullptr;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004474 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4475 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4476 FD = FTD->getTemplatedDecl();
4477 if (!HasExplicitTemplateArgs && !FD) {
4478 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4479 // If the Decl is neither a function nor a template function,
4480 // determine if it is a pointer or reference to a function. If so,
4481 // check against the number of arguments expected for the pointee.
4482 QualType ValType = cast<ValueDecl>(ND)->getType();
4483 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4484 ValType = ValType->getPointeeType();
4485 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004486 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004487 return true;
4488 }
4489 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004490
4491 // Skip the current candidate if it is not a FunctionDecl or does not accept
4492 // the current number of arguments.
4493 if (!FD || !(FD->getNumParams() >= NumArgs &&
4494 FD->getMinRequiredArguments() <= NumArgs))
4495 continue;
4496
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004497 // If the current candidate is a non-static C++ method, skip the candidate
4498 // unless the method being corrected--or the current DeclContext, if the
4499 // function being corrected is not a method--is a method in the same class
4500 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004501 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004502 if (MemberFn || !MD->isStatic()) {
4503 CXXMethodDecl *CurMD =
4504 MemberFn
4505 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4506 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004507 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004508 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004509 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4510 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4511 continue;
4512 }
4513 }
4514 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004515 }
4516 return false;
4517}
Richard Smithf9b15102013-08-17 00:46:16 +00004518
4519void Sema::diagnoseTypo(const TypoCorrection &Correction,
4520 const PartialDiagnostic &TypoDiag,
4521 bool ErrorRecovery) {
4522 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4523 ErrorRecovery);
4524}
4525
Richard Smithe156254d2013-08-20 20:35:18 +00004526/// Find which declaration we should import to provide the definition of
4527/// the given declaration.
4528static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4529 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4530 return VD->getDefinition();
4531 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00004532 return FD->isDefined(FD) ? FD : nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004533 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4534 return TD->getDefinition();
4535 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4536 return ID->getDefinition();
4537 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4538 return PD->getDefinition();
4539 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4540 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004541 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004542}
4543
Richard Smithf9b15102013-08-17 00:46:16 +00004544/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4545/// itself to allow external validation of the result, etc.
4546///
4547/// \param Correction The result of performing typo correction.
4548/// \param TypoDiag The diagnostic to produce. This will have the corrected
4549/// string added to it (and usually also a fixit).
4550/// \param PrevNote A note to use when indicating the location of the entity to
4551/// which we are correcting. Will have the correction string added to it.
4552/// \param ErrorRecovery If \c true (the default), the caller is going to
4553/// recover from the typo as if the corrected string had been typed.
4554/// In this case, \c PDiag must be an error, and we will attach a fixit
4555/// to it.
4556void Sema::diagnoseTypo(const TypoCorrection &Correction,
4557 const PartialDiagnostic &TypoDiag,
4558 const PartialDiagnostic &PrevNote,
4559 bool ErrorRecovery) {
4560 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4561 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4562 FixItHint FixTypo = FixItHint::CreateReplacement(
4563 Correction.getCorrectionRange(), CorrectedStr);
4564
Richard Smithe156254d2013-08-20 20:35:18 +00004565 // Maybe we're just missing a module import.
4566 if (Correction.requiresImport()) {
4567 NamedDecl *Decl = Correction.getCorrectionDecl();
4568 assert(Decl && "import required but no declaration to import");
4569
4570 // Suggest importing a module providing the definition of this entity, if
4571 // possible.
4572 const NamedDecl *Def = getDefinitionToImport(Decl);
4573 if (!Def)
4574 Def = Decl;
4575 Module *Owner = Def->getOwningModule();
4576 assert(Owner && "definition of hidden declaration is not in a module");
4577
4578 Diag(Correction.getCorrectionRange().getBegin(),
4579 diag::err_module_private_declaration)
4580 << Def << Owner->getFullModuleName();
4581 Diag(Def->getLocation(), diag::note_previous_declaration);
4582
4583 // Recover by implicitly importing this module.
Richard Smith3d23c422014-05-07 02:25:43 +00004584 if (ErrorRecovery)
4585 createImplicitModuleImportForErrorRecovery(
4586 Correction.getCorrectionRange().getBegin(), Owner);
Richard Smithe156254d2013-08-20 20:35:18 +00004587 return;
4588 }
4589
Richard Smithf9b15102013-08-17 00:46:16 +00004590 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4591 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4592
4593 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004594 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004595 if (PrevNote.getDiagID() && ChosenDecl)
4596 Diag(ChosenDecl->getLocation(), PrevNote)
4597 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4598}