blob: ebe28944062c0b76021fec89e4eef018ecc4df86 [file] [log] [blame]
Douglas Gregoreb11cd02009-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 Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewycky173a37a2012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ExternalSemaSource.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/TemplateDeduction.h"
34#include "clang/Sema/TypoCorrection.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/ADT/SetVector.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000038#include "llvm/ADT/StringMap.h"
Chris Lattnerb5f65472011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6e247262009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Nick Lewycky893a6ea2012-04-03 20:26:45 +000042#include <algorithm>
43#include <iterator>
Douglas Gregore24b5752010-10-14 20:34:08 +000044#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000045#include <list>
Douglas Gregord8bba9c2011-06-28 16:20:02 +000046#include <map>
Nick Lewycky893a6ea2012-04-03 20:26:45 +000047#include <set>
48#include <utility>
49#include <vector>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000050
51using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000052using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054namespace {
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000058
John McCalld7be78a2009-11-10 07:01:13 +000059 public:
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000064
John McCalld7be78a2009-11-10 07:01:13 +000065 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
67 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000068
John McCalld7be78a2009-11-10 07:01:13 +000069 const DeclContext *getNominatedNamespace() const {
70 return Nominated;
71 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000072
John McCalld7be78a2009-11-10 07:01:13 +000073 // Sort by the pointer value of the common ancestor.
74 struct Comparator {
75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76 return L.getCommonAncestor() < R.getCommonAncestor();
77 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000078
John McCalld7be78a2009-11-10 07:01:13 +000079 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
81 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000082
John McCalld7be78a2009-11-10 07:01:13 +000083 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
85 }
86 };
87 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000088
John McCalld7be78a2009-11-10 07:01:13 +000089 /// A collection of using directives, as used by C++ unqualified
90 /// lookup.
91 class UnqualUsingDirectiveSet {
Chris Lattner5f9e2722011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000096
John McCalld7be78a2009-11-10 07:01:13 +000097 public:
98 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000099
John McCalld7be78a2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCalld7be78a2009-11-10 07:01:13 +0000102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
105 DeclContext *InnermostFileDC
106 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000108
John McCalld7be78a2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky65daef12012-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.
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000113 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
Nick Lewycky65daef12012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
John McCalld7be78a2009-11-10 07:01:13 +0000117 Scope::udir_iterator I = S->using_directives_begin(),
118 End = S->using_directives_end();
John McCalld7be78a2009-11-10 07:01:13 +0000119 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000120 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000121 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000122 }
123 }
John McCalld7be78a2009-11-10 07:01:13 +0000124
125 // Visits a context and collect all of its using directives
126 // recursively. Treats all using directives as if they were
127 // declared in the context.
128 //
129 // A given context is only every visited once, so it is important
130 // that contexts be visited from the inside out in order to get
131 // the effective DCs right.
132 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
133 if (!visited.insert(DC))
134 return;
135
136 addUsingDirectives(DC, EffectiveDC);
137 }
138
139 // Visits a using directive and collects all of its using
140 // directives recursively. Treats all using directives as if they
141 // were declared in the effective DC.
142 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (!visited.insert(NS))
145 return;
146
147 addUsingDirective(UD, EffectiveDC);
148 addUsingDirectives(NS, EffectiveDC);
149 }
150
151 // Adds all the using directives in a context (and those nominated
152 // by its using directives, transitively) as if they appeared in
153 // the given effective context.
154 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000155 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-11-10 07:01:13 +0000156 while (true) {
157 DeclContext::udir_iterator I, End;
158 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
159 UsingDirectiveDecl *UD = *I;
160 DeclContext *NS = UD->getNominatedNamespace();
161 if (visited.insert(NS)) {
162 addUsingDirective(UD, EffectiveDC);
163 queue.push_back(NS);
164 }
165 }
166
167 if (queue.empty())
168 return;
169
170 DC = queue.back();
171 queue.pop_back();
172 }
173 }
174
175 // Add a using directive as if it had been declared in the given
176 // context. This helps implement C++ [namespace.udir]p3:
177 // The using-directive is transitive: if a scope contains a
178 // using-directive that nominates a second namespace that itself
179 // contains using-directives, the effect is as if the
180 // using-directives from the second namespace also appeared in
181 // the first.
182 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
183 // Find the common ancestor between the effective context and
184 // the nominated namespace.
185 DeclContext *Common = UD->getNominatedNamespace();
186 while (!Common->Encloses(EffectiveDC))
187 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000188 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000189
John McCalld7be78a2009-11-10 07:01:13 +0000190 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
191 }
192
193 void done() {
194 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
195 }
196
John McCalld7be78a2009-11-10 07:01:13 +0000197 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000198
John McCalld7be78a2009-11-10 07:01:13 +0000199 const_iterator begin() const { return list.begin(); }
200 const_iterator end() const { return list.end(); }
201
202 std::pair<const_iterator,const_iterator>
203 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000204 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000205 UnqualUsingEntry::Comparator());
206 }
207 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000208}
209
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210// Retrieve the set of identifier namespaces that correspond to a
211// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000212static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
213 bool CPlusPlus,
214 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000215 unsigned IDNS = 0;
216 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000217 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000218 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000219 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000220 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000221 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000222 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000223 if (Redeclaration)
224 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000225 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000226 break;
227
John McCall76d32642010-04-24 01:30:58 +0000228 case Sema::LookupOperatorName:
229 // Operator lookup is its own crazy thing; it is not the same
230 // as (e.g.) looking up an operator name for redeclaration.
231 assert(!Redeclaration && "cannot do redeclaration operator lookup");
232 IDNS = Decl::IDNS_NonMemberOperator;
233 break;
234
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000235 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000236 if (CPlusPlus) {
237 IDNS = Decl::IDNS_Type;
238
239 // When looking for a redeclaration of a tag name, we add:
240 // 1) TagFriend to find undeclared friend decls
241 // 2) Namespace because they can't "overload" with tag decls.
242 // 3) Tag because it includes class templates, which can't
243 // "overload" with tag decls.
244 if (Redeclaration)
245 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
246 } else {
247 IDNS = Decl::IDNS_Tag;
248 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000249 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000250 case Sema::LookupLabel:
251 IDNS = Decl::IDNS_Label;
252 break;
253
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000254 case Sema::LookupMemberName:
255 IDNS = Decl::IDNS_Member;
256 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000257 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000258 break;
259
260 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
262 break;
263
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000264 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000265 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000266 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000267
John McCall9f54ad42009-12-10 09:41:52 +0000268 case Sema::LookupUsingDeclName:
269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
270 | Decl::IDNS_Member | Decl::IDNS_Using;
271 break;
272
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000273 case Sema::LookupObjCProtocolName:
274 IDNS = Decl::IDNS_ObjCProtocol;
275 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276
Douglas Gregor8071e422010-08-15 06:18:01 +0000277 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000278 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000279 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
280 | Decl::IDNS_Type;
281 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000282 }
283 return IDNS;
284}
285
John McCall1d7c5282009-12-18 10:40:03 +0000286void LookupResult::configure() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000287 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000288 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000289
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000290 if (!isForRedeclaration()) {
Douglas Gregor96df3562013-04-03 23:06:26 +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.
Abramo Bagnara25777432010-08-11 22:01:17 +0000294 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000295 case OO_New:
296 case OO_Delete:
297 case OO_Array_New:
298 case OO_Array_Delete:
299 SemaRef.DeclareGlobalNewDelete();
300 break;
301
302 default:
303 break;
304 }
Douglas Gregor96df3562013-04-03 23:06:26 +0000305
306 // 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;
312 }
313 }
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000314 }
John McCall1d7c5282009-12-18 10:40:03 +0000315}
316
Daniel Dunbarc2bd73b2012-03-08 01:43:06 +0000317void LookupResult::sanityImpl() const {
318 // Note that this function is never called by NDEBUG builds. See
319 // LookupResult::sanity().
John McCall2a7fb272010-08-25 05:32:35 +0000320 assert(ResultKind != NotFound || Decls.size() == 0);
321 assert(ResultKind != Found || Decls.size() == 1);
322 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
323 (Decls.size() == 1 &&
324 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
325 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
326 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000327 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
328 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000329 assert((Paths != NULL) == (ResultKind == Ambiguous &&
330 (Ambiguity == AmbiguousBaseSubobjectTypes ||
331 Ambiguity == AmbiguousBaseSubobjects)));
332}
John McCall2a7fb272010-08-25 05:32:35 +0000333
John McCallf36e02d2009-10-09 21:13:30 +0000334// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000335void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000336 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000337}
338
Douglas Gregor55368912011-12-14 16:03:29 +0000339static NamedDecl *getVisibleDecl(NamedDecl *D);
340
341NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
342 return getVisibleDecl(D);
343}
344
John McCall7453ed42009-11-22 00:44:51 +0000345/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000346void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000347 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000348
John McCallf36e02d2009-10-09 21:13:30 +0000349 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000350 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000351 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000352 return;
353 }
354
John McCall7453ed42009-11-22 00:44:51 +0000355 // If there's a single decl, we need to examine it to decide what
356 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000357 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000358 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
359 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000360 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000361 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000362 ResultKind = FoundUnresolvedValue;
363 return;
364 }
John McCallf36e02d2009-10-09 21:13:30 +0000365
John McCall6e247262009-10-10 05:48:19 +0000366 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000367 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000368
John McCallf36e02d2009-10-09 21:13:30 +0000369 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000370 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000371
John McCallf36e02d2009-10-09 21:13:30 +0000372 bool Ambiguous = false;
373 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000374 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000375
376 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000377
John McCallf36e02d2009-10-09 21:13:30 +0000378 unsigned I = 0;
379 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000380 NamedDecl *D = Decls[I]->getUnderlyingDecl();
381 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000382
Argyrios Kyrtzidis745af1c2013-02-22 06:58:37 +0000383 // Ignore an invalid declaration unless it's the only one left.
384 if (D->isInvalidDecl() && I < N-1) {
385 Decls[I] = Decls[--N];
386 continue;
387 }
388
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000389 // Redeclarations of types via typedef can occur both within a scope
390 // and, through using declarations and directives, across scopes. There is
391 // no ambiguity if they all refer to the same type, so unique based on the
392 // canonical type.
393 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
394 if (!TD->getDeclContext()->isRecord()) {
395 QualType T = SemaRef.Context.getTypeDeclType(TD);
396 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
397 // The type is not unique; pull something off the back and continue
398 // at this index.
399 Decls[I] = Decls[--N];
400 continue;
401 }
402 }
403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000404
John McCall314be4e2009-11-17 07:50:12 +0000405 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000406 // If it's not unique, pull something off the back (and
407 // continue at this index).
408 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000409 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000410 }
411
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000412 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000413
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000414 if (isa<UnresolvedUsingValueDecl>(D)) {
415 HasUnresolved = true;
416 } else if (isa<TagDecl>(D)) {
417 if (HasTag)
418 Ambiguous = true;
419 UniqueTagIndex = I;
420 HasTag = true;
421 } else if (isa<FunctionTemplateDecl>(D)) {
422 HasFunction = true;
423 HasFunctionTemplate = true;
424 } else if (isa<FunctionDecl>(D)) {
425 HasFunction = true;
426 } else {
427 if (HasNonFunction)
428 Ambiguous = true;
429 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000430 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000431 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000432 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000433
John McCallf36e02d2009-10-09 21:13:30 +0000434 // C++ [basic.scope.hiding]p2:
435 // A class name or enumeration name can be hidden by the name of
436 // an object, function, or enumerator declared in the same
437 // scope. If a class or enumeration name and an object, function,
438 // or enumerator are declared in the same scope (in any order)
439 // with the same name, the class or enumeration name is hidden
440 // wherever the object, function, or enumerator name is visible.
441 // But it's still an error if there are distinct tag types found,
442 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000443 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000444 (HasFunction || HasNonFunction || HasUnresolved)) {
445 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
446 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
447 Decls[UniqueTagIndex] = Decls[--N];
448 else
449 Ambiguous = true;
450 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000451
John McCallf36e02d2009-10-09 21:13:30 +0000452 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000453
John McCallfda8e122009-12-03 00:58:24 +0000454 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000455 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000456
John McCallf36e02d2009-10-09 21:13:30 +0000457 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000458 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000459 else if (HasUnresolved)
460 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000461 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000462 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000463 else
John McCalla24dc2e2009-11-17 02:14:36 +0000464 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000465}
466
John McCall7d384dd2009-11-18 07:57:50 +0000467void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000468 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000469 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikie3bc93e32012-12-19 00:45:41 +0000470 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
471 DE = I->Decls.end(); DI != DE; ++DI)
John McCallf36e02d2009-10-09 21:13:30 +0000472 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000473}
474
John McCall7d384dd2009-11-18 07:57:50 +0000475void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000476 Paths = new CXXBasePaths;
477 Paths->swap(P);
478 addDeclsFromBasePaths(*Paths);
479 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000480 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000481}
482
John McCall7d384dd2009-11-18 07:57:50 +0000483void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000484 Paths = new CXXBasePaths;
485 Paths->swap(P);
486 addDeclsFromBasePaths(*Paths);
487 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000488 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000489}
490
Chris Lattner5f9e2722011-07-23 10:55:15 +0000491void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000492 Out << Decls.size() << " result(s)";
493 if (isAmbiguous()) Out << ", ambiguous";
494 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000495
John McCallf36e02d2009-10-09 21:13:30 +0000496 for (iterator I = begin(), E = end(); I != E; ++I) {
497 Out << "\n";
498 (*I)->print(Out, 2);
499 }
500}
501
Douglas Gregor85910982010-02-12 05:48:04 +0000502/// \brief Lookup a builtin function, when name lookup would otherwise
503/// fail.
504static bool LookupBuiltin(Sema &S, LookupResult &R) {
505 Sema::LookupNameKind NameKind = R.getLookupKind();
506
507 // If we didn't find a use of this identifier, and if the identifier
508 // corresponds to a compiler builtin, create the decl object for the builtin
509 // now, injecting it into translation unit scope, and return it.
510 if (NameKind == Sema::LookupOrdinaryName ||
511 NameKind == Sema::LookupRedeclarationWithLinkage) {
512 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
513 if (II) {
514 // If this is a builtin on this (or all) targets, create the decl.
515 if (unsigned BuiltinID = II->getBuiltinID()) {
516 // In C++, we don't have any predefined library functions like
517 // 'malloc'. Instead, we'll just error.
David Blaikie4e4d0842012-03-11 07:00:24 +0000518 if (S.getLangOpts().CPlusPlus &&
Douglas Gregor85910982010-02-12 05:48:04 +0000519 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
520 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000521
522 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
523 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000524 R.isForRedeclaration(),
525 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000526 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000527 return true;
528 }
529
530 if (R.isForRedeclaration()) {
531 // If we're redeclaring this function anyway, forget that
532 // this was a builtin at all.
533 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
534 }
535
536 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000537 }
538 }
539 }
540
541 return false;
542}
543
Douglas Gregor4923aa22010-07-02 20:37:36 +0000544/// \brief Determine whether we can declare a special member function within
545/// the class at this point.
Richard Smithd0adeb62012-11-27 21:20:31 +0000546static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +0000547 // We need to have a definition for the class.
548 if (!Class->getDefinition() || Class->isDependentContext())
549 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550
Douglas Gregor4923aa22010-07-02 20:37:36 +0000551 // We can't be in the middle of defining the class.
Richard Smithd0adeb62012-11-27 21:20:31 +0000552 return !Class->isBeingDefined();
Douglas Gregor4923aa22010-07-02 20:37:36 +0000553}
554
555void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000556 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregor22584312010-07-02 23:41:54 +0000557 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000558
559 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000560 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000561 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000562
Douglas Gregor22584312010-07-02 23:41:54 +0000563 // If the copy constructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000564 if (Class->needsImplicitCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +0000565 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566
Douglas Gregora376d102010-07-02 21:50:04 +0000567 // If the copy assignment operator has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000568 if (Class->needsImplicitCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000569 DeclareImplicitCopyAssignment(Class);
570
Richard Smith80ad52f2013-01-02 11:42:31 +0000571 if (getLangOpts().CPlusPlus11) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000572 // If the move constructor has not yet been declared, do so now.
573 if (Class->needsImplicitMoveConstructor())
574 DeclareImplicitMoveConstructor(Class); // might not actually do it
575
576 // If the move assignment operator has not yet been declared, do so now.
577 if (Class->needsImplicitMoveAssignment())
578 DeclareImplicitMoveAssignment(Class); // might not actually do it
579 }
580
Douglas Gregor4923aa22010-07-02 20:37:36 +0000581 // If the destructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000582 if (Class->needsImplicitDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000584}
585
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000587/// special member function.
588static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
589 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000590 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000591 case DeclarationName::CXXDestructorName:
592 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000593
Douglas Gregora376d102010-07-02 21:50:04 +0000594 case DeclarationName::CXXOperatorName:
595 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000596
Douglas Gregora376d102010-07-02 21:50:04 +0000597 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000599 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000600
Douglas Gregora376d102010-07-02 21:50:04 +0000601 return false;
602}
603
604/// \brief If there are any implicit member functions with the given name
605/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000606static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000607 DeclarationName Name,
608 const DeclContext *DC) {
609 if (!DC)
610 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000611
Douglas Gregora376d102010-07-02 21:50:04 +0000612 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000613 case DeclarationName::CXXConstructorName:
614 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithd0adeb62012-11-27 21:20:31 +0000615 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000616 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000617 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000618 S.DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +0000619 if (Record->needsImplicitCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000620 S.DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000621 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000622 Record->needsImplicitMoveConstructor())
623 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000624 }
Douglas Gregor22584312010-07-02 23:41:54 +0000625 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000626
Douglas Gregora376d102010-07-02 21:50:04 +0000627 case DeclarationName::CXXDestructorName:
628 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithe5411b72012-12-01 02:35:44 +0000629 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smithd0adeb62012-11-27 21:20:31 +0000630 CanDeclareSpecialMemberFunction(Record))
Douglas Gregora376d102010-07-02 21:50:04 +0000631 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000632 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000633
Douglas Gregora376d102010-07-02 21:50:04 +0000634 case DeclarationName::CXXOperatorName:
635 if (Name.getCXXOverloadedOperator() != OO_Equal)
636 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000637
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000638 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000639 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000640 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smithe5411b72012-12-01 02:35:44 +0000641 if (Record->needsImplicitCopyAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000642 S.DeclareImplicitCopyAssignment(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000643 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000644 Record->needsImplicitMoveAssignment())
645 S.DeclareImplicitMoveAssignment(Class);
646 }
647 }
Douglas Gregora376d102010-07-02 21:50:04 +0000648 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000649
Douglas Gregora376d102010-07-02 21:50:04 +0000650 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000651 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000652 }
653}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000654
John McCallf36e02d2009-10-09 21:13:30 +0000655// Adds all qualifying matches for a name within a decl context to the
656// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000657static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000658 bool Found = false;
659
Douglas Gregor4923aa22010-07-02 20:37:36 +0000660 // Lazily declare C++ special member functions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000661 if (S.getLangOpts().CPlusPlus)
Douglas Gregora376d102010-07-02 21:50:04 +0000662 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000663
Douglas Gregor4923aa22010-07-02 20:37:36 +0000664 // Perform lookup into this declaration context.
David Blaikie3bc93e32012-12-19 00:45:41 +0000665 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
666 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
667 ++I) {
John McCall46460a62010-01-20 21:53:11 +0000668 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000669 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000670 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000671 Found = true;
672 }
673 }
John McCallf36e02d2009-10-09 21:13:30 +0000674
Douglas Gregor85910982010-02-12 05:48:04 +0000675 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
676 return true;
677
Douglas Gregor48026d22010-01-11 18:40:55 +0000678 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000679 != DeclarationName::CXXConversionFunctionName ||
680 R.getLookupName().getCXXNameType()->isDependentType() ||
681 !isa<CXXRecordDecl>(DC))
682 return Found;
683
684 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000685 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000686 // name lookup. Instead, any conversion function templates visible in the
687 // context of the use are considered. [...]
688 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000689 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000690 return Found;
691
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +0000692 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
693 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000694 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
695 if (!ConvTemplate)
696 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000698 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000699 // add the conversion function template. When we deduce template
700 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000701 // type of the new declaration with the type of the function template.
702 if (R.isForRedeclaration()) {
703 R.addDecl(ConvTemplate);
704 Found = true;
705 continue;
706 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000707
Douglas Gregor48026d22010-01-11 18:40:55 +0000708 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000709 // [...] For each such operator, if argument deduction succeeds
710 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000711 // name lookup.
712 //
713 // When referencing a conversion function for any purpose other than
714 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000715 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000716 // specialization into the result set. We do this to avoid forcing all
717 // callers to perform special deduction for conversion functions.
Craig Topper93e45992012-09-19 02:26:47 +0000718 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000719 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000720
721 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000722 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
723 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000724
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000725 // Compute the type of the function that we would expect the conversion
726 // function to have, if it were to match the name given.
727 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000728 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
729 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000730 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000731 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000732 QualType ExpectedType
733 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Jordan Rosebea522f2013-03-08 21:51:21 +0000734 ArrayRef<QualType>(), EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000735
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000736 // Perform template argument deduction against the type that we would
737 // expect the function to have.
738 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
739 Specialization, Info)
740 == Sema::TDK_Success) {
741 R.addDecl(Specialization);
742 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000743 }
744 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000745
John McCallf36e02d2009-10-09 21:13:30 +0000746 return Found;
747}
748
John McCalld7be78a2009-11-10 07:01:13 +0000749// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000750static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000751CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000752 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000753
754 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
755
John McCalld7be78a2009-11-10 07:01:13 +0000756 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000757 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000758
John McCalld7be78a2009-11-10 07:01:13 +0000759 // Perform direct name lookup into the namespaces nominated by the
760 // using directives whose common ancestor is this namespace.
761 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
762 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000763
John McCalld7be78a2009-11-10 07:01:13 +0000764 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000765 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000766 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000767
768 R.resolveKind();
769
770 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000771}
772
773static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000774 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000775 return Ctx->isFileContext();
776 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000777}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000778
Douglas Gregor711be1e2010-03-15 14:33:29 +0000779// Find the next outer declaration context from this scope. This
780// routine actually returns the semantic outer context, which may
781// differ from the lexical context (encoded directly in the Scope
782// stack) when we are parsing a member of a class template. In this
783// case, the second element of the pair will be true, to indicate that
784// name lookup should continue searching in this semantic context when
785// it leaves the current template parameter scope.
786static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
787 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
788 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000789 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000790 OuterS = OuterS->getParent()) {
791 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000792 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000793 break;
794 }
795 }
796
797 // C++ [temp.local]p8:
798 // In the definition of a member of a class template that appears
799 // outside of the namespace containing the class template
800 // definition, the name of a template-parameter hides the name of
801 // a member of this namespace.
802 //
803 // Example:
804 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000805 // namespace N {
806 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000807 //
808 // template<class T> class B {
809 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000810 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000811 // }
812 //
813 // template<class C> void N::B<C>::f(C) {
814 // C b; // C is the template parameter, not N::C
815 // }
816 //
817 // In this example, the lexical context we return is the
818 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000819 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000820 !S->getParent()->isTemplateParamScope())
821 return std::make_pair(Lexical, false);
822
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000823 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000824 // For the example, this is the scope for the template parameters of
825 // template<class C>.
826 Scope *OutermostTemplateScope = S->getParent();
827 while (OutermostTemplateScope->getParent() &&
828 OutermostTemplateScope->getParent()->isTemplateParamScope())
829 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000830
Douglas Gregor711be1e2010-03-15 14:33:29 +0000831 // Find the namespace context in which the original scope occurs. In
832 // the example, this is namespace N.
833 DeclContext *Semantic = DC;
834 while (!Semantic->isFileContext())
835 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000836
Douglas Gregor711be1e2010-03-15 14:33:29 +0000837 // Find the declaration context just outside of the template
838 // parameter scope. This is the context in which the template is
839 // being lexically declaration (a namespace context). In the
840 // example, this is the global scope.
841 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
842 Lexical->Encloses(Semantic))
843 return std::make_pair(Semantic, true);
844
845 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000846}
847
John McCalla24dc2e2009-11-17 02:14:36 +0000848bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000849 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000850
851 DeclarationName Name = R.getLookupName();
852
Douglas Gregora376d102010-07-02 21:50:04 +0000853 // If this is the name of an implicitly-declared special member function,
854 // go through the scope stack to implicitly declare
855 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
856 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
857 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
858 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
859 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000860
Douglas Gregora376d102010-07-02 21:50:04 +0000861 // Implicitly declare member functions with the name we're looking for, if in
862 // fact we are in a scope where it matters.
863
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000864 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000865 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000866 I = IdResolver.begin(Name),
867 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000868
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000869 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000870 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000871 // ...During unqualified name lookup (3.4.1), the names appear as if
872 // they were declared in the nearest enclosing namespace which contains
873 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000874 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000875 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000876 //
877 // For example:
878 // namespace A { int i; }
879 // void foo() {
880 // int i;
881 // {
882 // using namespace A;
883 // ++i; // finds local 'i', A::i appears at global scope
884 // }
885 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000886 //
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000887 UnqualUsingDirectiveSet UDirs;
888 bool VisitedUsingDirectives = false;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000889 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000890 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000891 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
892
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000893 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000894 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000895 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000896 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000897 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000898 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000899 }
900 }
John McCallf36e02d2009-10-09 21:13:30 +0000901 if (Found) {
902 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000903 if (S->isClassScope())
904 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
905 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000906 return true;
907 }
908
Douglas Gregor711be1e2010-03-15 14:33:29 +0000909 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
910 S->getParent() && !S->getParent()->isTemplateParamScope()) {
911 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000912 // found nothing, so look into the contexts between the
Douglas Gregor711be1e2010-03-15 14:33:29 +0000913 // lexical and semantic declaration contexts returned by
914 // findOuterContext(). This implements the name lookup behavior
915 // of C++ [temp.local]p8.
916 Ctx = OutsideOfTemplateParamDC;
917 OutsideOfTemplateParamDC = 0;
918 }
919
920 if (Ctx) {
921 DeclContext *OuterCtx;
922 bool SearchAfterTemplateScope;
923 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
924 if (SearchAfterTemplateScope)
925 OutsideOfTemplateParamDC = OuterCtx;
926
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000927 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000928 // We do not directly look into transparent contexts, since
929 // those entities will be found in the nearest enclosing
930 // non-transparent context.
931 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000932 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000933
934 // We do not look directly into function or method contexts,
935 // since all of the local variables and parameters of the
936 // function/method are present within the Scope.
937 if (Ctx->isFunctionOrMethod()) {
938 // If we have an Objective-C instance method, look for ivars
939 // in the corresponding interface.
940 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
941 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
942 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
943 ObjCInterfaceDecl *ClassDeclared;
944 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000945 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000946 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000947 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
948 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000949 R.resolveKind();
950 return true;
951 }
952 }
953 }
954 }
955
956 continue;
957 }
958
Douglas Gregor6bed88e2013-03-27 12:51:49 +0000959 // If this is a file context, we need to perform unqualified name
960 // lookup considering using directives.
961 if (Ctx->isFileContext()) {
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000962 // If we haven't handled using directives yet, do so now.
963 if (!VisitedUsingDirectives) {
964 // Add using directives from this context up to the top level.
965 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent())
966 UDirs.visit(UCtx, UCtx);
967
968 // Find the innermost file scope, so we can add using directives
969 // from local scopes.
970 Scope *InnermostFileScope = S;
971 while (InnermostFileScope &&
972 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
973 InnermostFileScope = InnermostFileScope->getParent();
974 UDirs.visitScopeChain(Initial, InnermostFileScope);
975
976 UDirs.done();
977
978 VisitedUsingDirectives = true;
979 }
Douglas Gregor6bed88e2013-03-27 12:51:49 +0000980
981 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
982 R.resolveKind();
983 return true;
984 }
985
986 continue;
987 }
988
Douglas Gregore942bbe2009-09-10 16:57:35 +0000989 // Perform qualified name lookup into this context.
990 // FIXME: In some cases, we know that every name that could be found by
991 // this qualified name lookup will also be on the identifier chain. For
992 // example, inside a class without any base classes, we never need to
993 // perform qualified lookup because all of the members are on top of the
994 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000995 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000996 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000997 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000998 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000999 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001000
John McCalld7be78a2009-11-10 07:01:13 +00001001 // Stop if we ran out of scopes.
1002 // FIXME: This really, really shouldn't be happening.
1003 if (!S) return false;
1004
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001005 // If we are looking for members, no need to look into global/namespace scope.
1006 if (R.getLookupKind() == LookupMemberName)
1007 return false;
1008
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001009 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001010 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +00001011 //
Mike Stump390b4cc2009-05-16 07:39:55 +00001012 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1013 // don't build it for each lookup!
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001014 if (!VisitedUsingDirectives) {
1015 UDirs.visitScopeChain(Initial, S);
1016 UDirs.done();
1017 }
1018
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001019 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001020 // Unqualified name lookup in C++ requires looking into scopes
1021 // that aren't strictly lexical, and therefore we walk through the
1022 // context as well as walking through the scopes.
1023 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001024 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +00001025 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +00001026 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +00001027 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001028 // We found something. Look for anything else in our scope
1029 // with this same name and in an acceptable identifier
1030 // namespace, so that we can construct an overload set if we
1031 // need to.
John McCallf36e02d2009-10-09 21:13:30 +00001032 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +00001033 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001034 }
1035 }
1036
Douglas Gregor00b4b032010-05-14 04:53:42 +00001037 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +00001038 R.resolveKind();
1039 return true;
1040 }
1041
Douglas Gregor00b4b032010-05-14 04:53:42 +00001042 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1043 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1044 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1045 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001046 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001047 // lexical and semantic declaration contexts returned by
1048 // findOuterContext(). This implements the name lookup behavior
1049 // of C++ [temp.local]p8.
1050 Ctx = OutsideOfTemplateParamDC;
1051 OutsideOfTemplateParamDC = 0;
1052 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053
Douglas Gregor00b4b032010-05-14 04:53:42 +00001054 if (Ctx) {
1055 DeclContext *OuterCtx;
1056 bool SearchAfterTemplateScope;
1057 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1058 if (SearchAfterTemplateScope)
1059 OutsideOfTemplateParamDC = OuterCtx;
1060
1061 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1062 // We do not directly look into transparent contexts, since
1063 // those entities will be found in the nearest enclosing
1064 // non-transparent context.
1065 if (Ctx->isTransparentContext())
1066 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001067
Douglas Gregor00b4b032010-05-14 04:53:42 +00001068 // If we have a context, and it's not a context stashed in the
1069 // template parameter scope for an out-of-line definition, also
1070 // look into that context.
1071 if (!(Found && S && S->isTemplateParamScope())) {
1072 assert(Ctx->isFileContext() &&
1073 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001074
Douglas Gregor00b4b032010-05-14 04:53:42 +00001075 // Look into context considering using-directives.
1076 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1077 Found = true;
1078 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001079
Douglas Gregor00b4b032010-05-14 04:53:42 +00001080 if (Found) {
1081 R.resolveKind();
1082 return true;
1083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001084
Douglas Gregor00b4b032010-05-14 04:53:42 +00001085 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1086 return false;
1087 }
1088 }
1089
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001090 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001091 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001092 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001093
John McCallf36e02d2009-10-09 21:13:30 +00001094 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001095}
1096
Douglas Gregor55368912011-12-14 16:03:29 +00001097/// \brief Retrieve the visible declaration corresponding to D, if any.
1098///
1099/// This routine determines whether the declaration D is visible in the current
1100/// module, with the current imports. If not, it checks whether any
1101/// redeclaration of D is visible, and if so, returns that declaration.
1102///
1103/// \returns D, or a visible previous declaration of D, whichever is more recent
1104/// and visible. If no declaration of D is visible, returns null.
1105static NamedDecl *getVisibleDecl(NamedDecl *D) {
1106 if (LookupResult::isVisible(D))
1107 return D;
1108
Douglas Gregor0782ef22012-01-06 22:05:37 +00001109 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1110 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001111 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Douglas Gregor0782ef22012-01-06 22:05:37 +00001112 if (LookupResult::isVisible(ND))
1113 return ND;
1114 }
Douglas Gregor55368912011-12-14 16:03:29 +00001115 }
1116
1117 return 0;
1118}
1119
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001120/// @brief Perform unqualified name lookup starting from a given
1121/// scope.
1122///
1123/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1124/// used to find names within the current scope. For example, 'x' in
1125/// @code
1126/// int x;
1127/// int f() {
1128/// return x; // unqualified name look finds 'x' in the global scope
1129/// }
1130/// @endcode
1131///
1132/// Different lookup criteria can find different names. For example, a
1133/// particular scope can have both a struct and a function of the same
1134/// name, and each can be found by certain lookup criteria. For more
1135/// information about lookup criteria, see the documentation for the
1136/// class LookupCriteria.
1137///
1138/// @param S The scope from which unqualified name lookup will
1139/// begin. If the lookup criteria permits, name lookup may also search
1140/// in the parent scopes.
1141///
James Dennett8da16872012-06-22 10:32:46 +00001142/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1143/// look up and the lookup kind), and is updated with the results of lookup
1144/// including zero or more declarations and possibly additional information
1145/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001146///
James Dennett8da16872012-06-22 10:32:46 +00001147/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001148bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1149 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001150 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001151
John McCalla24dc2e2009-11-17 02:14:36 +00001152 LookupNameKind NameKind = R.getLookupKind();
1153
David Blaikie4e4d0842012-03-11 07:00:24 +00001154 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001155 // Unqualified name lookup in C/Objective-C is purely lexical, so
1156 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001157 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001158 // Find the nearest non-transparent declaration scope.
1159 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001160 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001161 static_cast<DeclContext *>(S->getEntity())
1162 ->isTransparentContext()))
1163 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001164 }
1165
John McCall1d7c5282009-12-18 10:40:03 +00001166 unsigned IDNS = R.getIdentifierNamespace();
1167
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001168 // Scan up the scope chain looking for a decl that matches this
1169 // identifier that is in the appropriate namespace. This search
1170 // should not take long, as shadowing of names is uncommon, and
1171 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001172 bool LeftStartingScope = false;
1173
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001174 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001175 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001176 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001177 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001178 if (NameKind == LookupRedeclarationWithLinkage) {
1179 // Determine whether this (or a previous) declaration is
1180 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001181 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001182 LeftStartingScope = true;
1183
1184 // If we found something outside of our starting scope that
1185 // does not have linkage, skip it.
1186 if (LeftStartingScope && !((*I)->hasLinkage()))
1187 continue;
1188 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001189 else if (NameKind == LookupObjCImplicitSelfParam &&
1190 !isa<ImplicitParamDecl>(*I))
1191 continue;
1192
Douglas Gregor10ce9322011-12-02 20:08:44 +00001193 // If this declaration is module-private and it came from an AST
1194 // file, we can't see it.
Douglas Gregor447af242012-01-05 01:11:47 +00001195 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor55368912011-12-14 16:03:29 +00001196 if (!D)
Douglas Gregor10ce9322011-12-02 20:08:44 +00001197 continue;
Douglas Gregor55368912011-12-14 16:03:29 +00001198
1199 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001200
Douglas Gregor7a537402012-01-03 23:26:26 +00001201 // Check whether there are any other declarations with the same name
1202 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001203 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001204 // Find the scope in which this declaration was declared (if it
1205 // actually exists in a Scope).
1206 while (S && !S->isDeclScope(D))
1207 S = S->getParent();
1208
1209 // If the scope containing the declaration is the translation unit,
1210 // then we'll need to perform our checks based on the matching
1211 // DeclContexts rather than matching scopes.
1212 if (S && isNamespaceOrTranslationUnitScope(S))
1213 S = 0;
1214
1215 // Compute the DeclContext, if we need it.
1216 DeclContext *DC = 0;
1217 if (!S)
1218 DC = (*I)->getDeclContext()->getRedeclContext();
1219
Douglas Gregorda795b42012-01-04 16:44:10 +00001220 IdentifierResolver::iterator LastI = I;
1221 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001222 if (S) {
1223 // Match based on scope.
1224 if (!S->isDeclScope(*LastI))
1225 break;
1226 } else {
1227 // Match based on DeclContext.
1228 DeclContext *LastDC
1229 = (*LastI)->getDeclContext()->getRedeclContext();
1230 if (!LastDC->Equals(DC))
1231 break;
1232 }
1233
1234 // If the declaration isn't in the right namespace, skip it.
Douglas Gregorda795b42012-01-04 16:44:10 +00001235 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1236 continue;
Douglas Gregor117c4562012-01-13 23:06:53 +00001237
Douglas Gregor447af242012-01-05 01:11:47 +00001238 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregorda795b42012-01-04 16:44:10 +00001239 if (D)
1240 R.addDecl(D);
1241 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001242
Douglas Gregorda795b42012-01-04 16:44:10 +00001243 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001244 }
John McCallf36e02d2009-10-09 21:13:30 +00001245 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001246 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001247 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001248 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001249 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001250 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001251 }
1252
1253 // If we didn't find a use of this identifier, and if the identifier
1254 // corresponds to a compiler builtin, create the decl object for the builtin
1255 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001256 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1257 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001258
Axel Naumannf8291a12011-02-24 16:47:47 +00001259 // If we didn't find a use of this identifier, the ExternalSource
1260 // may be able to handle the situation.
1261 // Note: some lookup failures are expected!
1262 // See e.g. R.isForRedeclaration().
1263 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001264}
1265
John McCall6e247262009-10-10 05:48:19 +00001266/// @brief Perform qualified name lookup in the namespaces nominated by
1267/// using directives by the given context.
1268///
1269/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001270/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001271/// (where X is the global namespace), let S be the set of all
1272/// declarations of m in X and in the transitive closure of all
1273/// namespaces nominated by using-directives in X and its used
1274/// namespaces, except that using-directives are ignored in any
1275/// namespace, including X, directly containing one or more
1276/// declarations of m. No namespace is searched more than once in
1277/// the lookup of a name. If S is the empty set, the program is
1278/// ill-formed. Otherwise, if S has exactly one member, or if the
1279/// context of the reference is a using-declaration
1280/// (namespace.udecl), S is the required set of declarations of
1281/// m. Otherwise if the use of m is not one that allows a unique
1282/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001283///
John McCall6e247262009-10-10 05:48:19 +00001284/// C++98 [namespace.qual]p5:
1285/// During the lookup of a qualified namespace member name, if the
1286/// lookup finds more than one declaration of the member, and if one
1287/// declaration introduces a class name or enumeration name and the
1288/// other declarations either introduce the same object, the same
1289/// enumerator or a set of functions, the non-type name hides the
1290/// class or enumeration name if and only if the declarations are
1291/// from the same namespace; otherwise (the declarations are from
1292/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001293static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001294 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001295 assert(StartDC->isFileContext() && "start context is not a file context");
1296
1297 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1298 DeclContext::udir_iterator E = StartDC->using_directives_end();
1299
1300 if (I == E) return false;
1301
1302 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001303 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001304 Visited.insert(StartDC);
1305
1306 // We have not yet looked into these namespaces, much less added
1307 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001308 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001309
1310 // We have already looked into the initial namespace; seed the queue
1311 // with its using-children.
1312 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001313 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001314 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001315 Queue.push_back(ND);
1316 }
1317
1318 // The easiest way to implement the restriction in [namespace.qual]p5
1319 // is to check whether any of the individual results found a tag
1320 // and, if so, to declare an ambiguity if the final result is not
1321 // a tag.
1322 bool FoundTag = false;
1323 bool FoundNonTag = false;
1324
John McCall7d384dd2009-11-18 07:57:50 +00001325 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001326
1327 bool Found = false;
1328 while (!Queue.empty()) {
1329 NamespaceDecl *ND = Queue.back();
1330 Queue.pop_back();
1331
1332 // We go through some convolutions here to avoid copying results
1333 // between LookupResults.
1334 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001335 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001336 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001337
1338 if (FoundDirect) {
1339 // First do any local hiding.
1340 DirectR.resolveKind();
1341
1342 // If the local result is a tag, remember that.
1343 if (DirectR.isSingleTagDecl())
1344 FoundTag = true;
1345 else
1346 FoundNonTag = true;
1347
1348 // Append the local results to the total results if necessary.
1349 if (UseLocal) {
1350 R.addAllDecls(LocalR);
1351 LocalR.clear();
1352 }
1353 }
1354
1355 // If we find names in this namespace, ignore its using directives.
1356 if (FoundDirect) {
1357 Found = true;
1358 continue;
1359 }
1360
1361 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1362 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001363 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001364 Queue.push_back(Nom);
1365 }
1366 }
1367
1368 if (Found) {
1369 if (FoundTag && FoundNonTag)
1370 R.setAmbiguousQualifiedTagHiding();
1371 else
1372 R.resolveKind();
1373 }
1374
1375 return Found;
1376}
1377
Douglas Gregor8071e422010-08-15 06:18:01 +00001378/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001379static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001380 CXXBasePath &Path,
1381 void *Name) {
1382 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001383
Douglas Gregor8071e422010-08-15 06:18:01 +00001384 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1385 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001386 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001387}
1388
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001390/// static members, nested types, and enumerators.
1391template<typename InputIterator>
1392static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1393 Decl *D = (*First)->getUnderlyingDecl();
1394 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1395 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001396
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001397 if (isa<CXXMethodDecl>(D)) {
1398 // Determine whether all of the methods are static.
1399 bool AllMethodsAreStatic = true;
1400 for(; First != Last; ++First) {
1401 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001403 if (!isa<CXXMethodDecl>(D)) {
1404 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1405 break;
1406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001407
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001408 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1409 AllMethodsAreStatic = false;
1410 break;
1411 }
1412 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001413
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001414 if (AllMethodsAreStatic)
1415 return true;
1416 }
1417
1418 return false;
1419}
1420
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001421/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001422///
1423/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1424/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001425/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001426///
1427/// Different lookup criteria can find different names. For example, a
1428/// particular scope can have both a struct and a function of the same
1429/// name, and each can be found by certain lookup criteria. For more
1430/// information about lookup criteria, see the documentation for the
1431/// class LookupCriteria.
1432///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001433/// \param R captures both the lookup criteria and any lookup results found.
1434///
1435/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001436/// search. If the lookup criteria permits, name lookup may also search
1437/// in the parent contexts or (for C++ classes) base classes.
1438///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001439/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001440/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001441///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001442/// \returns true if lookup succeeded, false if it failed.
1443bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1444 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001445 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001446
John McCalla24dc2e2009-11-17 02:14:36 +00001447 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001448 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001450 // Make sure that the declaration context is complete.
1451 assert((!isa<TagDecl>(LookupCtx) ||
1452 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001453 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001454 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001455 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001457 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001458 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001459 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001460 if (isa<CXXRecordDecl>(LookupCtx))
1461 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001462 return true;
1463 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001464
John McCall6e247262009-10-10 05:48:19 +00001465 // Don't descend into implied contexts for redeclarations.
1466 // C++98 [namespace.qual]p6:
1467 // In a declaration for a namespace member in which the
1468 // declarator-id is a qualified-id, given that the qualified-id
1469 // for the namespace member has the form
1470 // nested-name-specifier unqualified-id
1471 // the unqualified-id shall name a member of the namespace
1472 // designated by the nested-name-specifier.
1473 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001474 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001475 return false;
1476
John McCalla24dc2e2009-11-17 02:14:36 +00001477 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001478 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001479 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001480
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001481 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001482 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001483 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001484 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001485 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001486
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001487 // If we're performing qualified name lookup into a dependent class,
1488 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001489 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001490 // template instantiation time (at which point all bases will be available)
1491 // or we have to fail.
1492 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1493 LookupRec->hasAnyDependentBases()) {
1494 R.setNotFoundInCurrentInstantiation();
1495 return false;
1496 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001497
Douglas Gregor7176fff2009-01-15 00:26:24 +00001498 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 CXXBasePaths Paths;
1500 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001501
1502 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001504 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001505 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001506 case LookupOrdinaryName:
1507 case LookupMemberName:
1508 case LookupRedeclarationWithLinkage:
1509 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1510 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001511
Douglas Gregora8f32e02009-10-06 17:59:45 +00001512 case LookupTagName:
1513 BaseCallback = &CXXRecordDecl::FindTagMember;
1514 break;
John McCall9f54ad42009-12-10 09:41:52 +00001515
Douglas Gregor8071e422010-08-15 06:18:01 +00001516 case LookupAnyName:
1517 BaseCallback = &LookupAnyMember;
1518 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001519
John McCall9f54ad42009-12-10 09:41:52 +00001520 case LookupUsingDeclName:
1521 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001522
Douglas Gregora8f32e02009-10-06 17:59:45 +00001523 case LookupOperatorName:
1524 case LookupNamespaceName:
1525 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001526 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001527 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001528 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001529
Douglas Gregora8f32e02009-10-06 17:59:45 +00001530 case LookupNestedNameSpecifierName:
1531 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1532 break;
1533 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001534
John McCalla24dc2e2009-11-17 02:14:36 +00001535 if (!LookupRec->lookupInBases(BaseCallback,
1536 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001537 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001538
John McCall92f88312010-01-23 00:46:32 +00001539 R.setNamingClass(LookupRec);
1540
Douglas Gregor7176fff2009-01-15 00:26:24 +00001541 // C++ [class.member.lookup]p2:
1542 // [...] If the resulting set of declarations are not all from
1543 // sub-objects of the same type, or the set has a nonstatic member
1544 // and includes members from distinct sub-objects, there is an
1545 // ambiguity and the program is ill-formed. Otherwise that set is
1546 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001547 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001548 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001549 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001550
Douglas Gregora8f32e02009-10-06 17:59:45 +00001551 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001552 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001553 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001554
John McCall46460a62010-01-20 21:53:11 +00001555 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1556 // across all paths.
1557 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001558
Douglas Gregor7176fff2009-01-15 00:26:24 +00001559 // Determine whether we're looking at a distinct sub-object or not.
1560 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001561 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001562 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1563 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001564 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001565 }
1566
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001567 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001568 != Context.getCanonicalType(PathElement.Base->getType())) {
1569 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001570 // different types. If the declaration sets aren't the same, this
1571 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001572 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001573 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001574 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1575 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001576
David Blaikie3bc93e32012-12-19 00:45:41 +00001577 while (FirstD != FirstPath->Decls.end() &&
1578 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001579 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1580 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1581 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001582
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001583 ++FirstD;
1584 ++CurrentD;
1585 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001586
David Blaikie3bc93e32012-12-19 00:45:41 +00001587 if (FirstD == FirstPath->Decls.end() &&
1588 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001589 continue;
1590 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001591
John McCallf36e02d2009-10-09 21:13:30 +00001592 R.setAmbiguousBaseSubobjectTypes(Paths);
1593 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001594 }
1595
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001596 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001597 // We have a different subobject of the same type.
1598
1599 // C++ [class.member.lookup]p5:
1600 // A static member, a nested type or an enumerator defined in
1601 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001602 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001603 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001604 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001605
Douglas Gregor7176fff2009-01-15 00:26:24 +00001606 // We have found a nonstatic member name in multiple, distinct
1607 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001608 R.setAmbiguousBaseSubobjects(Paths);
1609 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001610 }
1611 }
1612
1613 // Lookup in a base class succeeded; return these results.
1614
David Blaikie3bc93e32012-12-19 00:45:41 +00001615 DeclContext::lookup_result DR = Paths.front().Decls;
1616 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001617 NamedDecl *D = *I;
1618 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1619 D->getAccess());
1620 R.addDecl(D, AS);
1621 }
John McCallf36e02d2009-10-09 21:13:30 +00001622 R.resolveKind();
1623 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001624}
1625
1626/// @brief Performs name lookup for a name that was parsed in the
1627/// source code, and may contain a C++ scope specifier.
1628///
1629/// This routine is a convenience routine meant to be called from
1630/// contexts that receive a name and an optional C++ scope specifier
1631/// (e.g., "N::M::x"). It will then perform either qualified or
1632/// unqualified name lookup (with LookupQualifiedName or LookupName,
1633/// respectively) on the given name and return those results.
1634///
1635/// @param S The scope from which unqualified name lookup will
1636/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001637///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001638/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001639///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001640/// @param EnteringContext Indicates whether we are going to enter the
1641/// context of the scope-specifier SS (if present).
1642///
John McCallf36e02d2009-10-09 21:13:30 +00001643/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001644bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001645 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001646 if (SS && SS->isInvalid()) {
1647 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001648 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001649 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Douglas Gregor495c35d2009-08-25 22:51:20 +00001652 if (SS && SS->isSet()) {
1653 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001654 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001655 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001656 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001657 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001658
John McCalla24dc2e2009-11-17 02:14:36 +00001659 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001660 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001661 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001662
Douglas Gregor495c35d2009-08-25 22:51:20 +00001663 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001664 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001665 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001666 R.setNotFoundInCurrentInstantiation();
1667 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001668 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001669 }
1670
Mike Stump1eb44332009-09-09 15:08:12 +00001671 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001672 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001673}
1674
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001675
James Dennett16ae9de2012-06-22 10:16:05 +00001676/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001677/// from name lookup.
1678///
James Dennett16ae9de2012-06-22 10:16:05 +00001679/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump1eb44332009-09-09 15:08:12 +00001680///
James Dennett16ae9de2012-06-22 10:16:05 +00001681/// \returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001682bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001683 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1684
John McCalla24dc2e2009-11-17 02:14:36 +00001685 DeclarationName Name = Result.getLookupName();
1686 SourceLocation NameLoc = Result.getNameLoc();
1687 SourceRange LookupRange = Result.getContextRange();
1688
John McCall6e247262009-10-10 05:48:19 +00001689 switch (Result.getAmbiguityKind()) {
1690 case LookupResult::AmbiguousBaseSubobjects: {
1691 CXXBasePaths *Paths = Result.getBasePaths();
1692 QualType SubobjectType = Paths->front().back().Base->getType();
1693 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1694 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1695 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001696
David Blaikie3bc93e32012-12-19 00:45:41 +00001697 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001698 while (isa<CXXMethodDecl>(*Found) &&
1699 cast<CXXMethodDecl>(*Found)->isStatic())
1700 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001701
John McCall6e247262009-10-10 05:48:19 +00001702 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001703
John McCall6e247262009-10-10 05:48:19 +00001704 return true;
1705 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001706
John McCall6e247262009-10-10 05:48:19 +00001707 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001708 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1709 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001710
John McCall6e247262009-10-10 05:48:19 +00001711 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001712 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001713 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1714 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001715 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001716 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001717 if (DeclsPrinted.insert(D).second)
1718 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1719 }
1720
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001721 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001722 }
1723
John McCall6e247262009-10-10 05:48:19 +00001724 case LookupResult::AmbiguousTagHiding: {
1725 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001726
John McCall6e247262009-10-10 05:48:19 +00001727 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1728
1729 LookupResult::iterator DI, DE = Result.end();
1730 for (DI = Result.begin(); DI != DE; ++DI)
1731 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1732 TagDecls.insert(TD);
1733 Diag(TD->getLocation(), diag::note_hidden_tag);
1734 }
1735
1736 for (DI = Result.begin(); DI != DE; ++DI)
1737 if (!isa<TagDecl>(*DI))
1738 Diag((*DI)->getLocation(), diag::note_hiding_object);
1739
1740 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001741 LookupResult::Filter F = Result.makeFilter();
1742 while (F.hasNext()) {
1743 if (TagDecls.count(F.next()))
1744 F.erase();
1745 }
1746 F.done();
John McCall6e247262009-10-10 05:48:19 +00001747
1748 return true;
1749 }
1750
1751 case LookupResult::AmbiguousReference: {
1752 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001753
John McCall6e247262009-10-10 05:48:19 +00001754 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1755 for (; DI != DE; ++DI)
1756 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001757
John McCall6e247262009-10-10 05:48:19 +00001758 return true;
1759 }
1760 }
1761
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001762 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001763}
Douglas Gregorfa047642009-02-04 00:32:51 +00001764
John McCallc7e04da2010-05-28 18:45:08 +00001765namespace {
1766 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001767 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001768 Sema::AssociatedNamespaceSet &Namespaces,
1769 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001770 : S(S), Namespaces(Namespaces), Classes(Classes),
1771 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001772 }
1773
1774 Sema &S;
1775 Sema::AssociatedNamespaceSet &Namespaces;
1776 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001777 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001778 };
1779}
1780
Mike Stump1eb44332009-09-09 15:08:12 +00001781static void
John McCallc7e04da2010-05-28 18:45:08 +00001782addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001783
Douglas Gregor54022952010-04-30 07:08:38 +00001784static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1785 DeclContext *Ctx) {
1786 // Add the associated namespace for this class.
1787
1788 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1789 // be a locally scoped record.
1790
Sebastian Redl410c4f22010-08-31 20:53:31 +00001791 // We skip out of inline namespaces. The innermost non-inline namespace
1792 // contains all names of all its nested inline namespaces anyway, so we can
1793 // replace the entire inline namespace tree with its root.
1794 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1795 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001796 Ctx = Ctx->getParent();
1797
John McCall6ff07852009-08-07 22:18:02 +00001798 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001799 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001800}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001801
Mike Stump1eb44332009-09-09 15:08:12 +00001802// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001803// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001804static void
John McCallc7e04da2010-05-28 18:45:08 +00001805addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1806 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001807 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001808 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001809 switch (Arg.getKind()) {
1810 case TemplateArgument::Null:
1811 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Douglas Gregor69be8d62009-07-08 07:51:57 +00001813 case TemplateArgument::Type:
1814 // [...] the namespaces and classes associated with the types of the
1815 // template arguments provided for template type parameters (excluding
1816 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001817 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001818 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001819
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001820 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001821 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001822 // [...] the namespaces in which any template template arguments are
1823 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001824 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001825 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001826 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001827 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001828 DeclContext *Ctx = ClassTemplate->getDeclContext();
1829 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001830 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001831 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001832 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001833 }
1834 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001835 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001836
Douglas Gregor788cd062009-11-11 01:00:40 +00001837 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001838 case TemplateArgument::Integral:
1839 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001840 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001841 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001842 // associated namespaces. ]
1843 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Douglas Gregor69be8d62009-07-08 07:51:57 +00001845 case TemplateArgument::Pack:
1846 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1847 PEnd = Arg.pack_end();
1848 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001849 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001850 break;
1851 }
1852}
1853
Douglas Gregorfa047642009-02-04 00:32:51 +00001854// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001855// argument-dependent lookup with an argument of class type
1856// (C++ [basic.lookup.koenig]p2).
1857static void
John McCallc7e04da2010-05-28 18:45:08 +00001858addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1859 CXXRecordDecl *Class) {
1860
1861 // Just silently ignore anything whose name is __va_list_tag.
1862 if (Class->getDeclName() == Result.S.VAListTagName)
1863 return;
1864
Douglas Gregorfa047642009-02-04 00:32:51 +00001865 // C++ [basic.lookup.koenig]p2:
1866 // [...]
1867 // -- If T is a class type (including unions), its associated
1868 // classes are: the class itself; the class of which it is a
1869 // member, if any; and its direct and indirect base
1870 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001871 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001872
1873 // Add the class of which it is a member, if any.
1874 DeclContext *Ctx = Class->getDeclContext();
1875 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001876 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001877 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001878 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Douglas Gregorfa047642009-02-04 00:32:51 +00001880 // Add the class itself. If we've already seen this class, we don't
1881 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001882 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001883 return;
1884
Mike Stump1eb44332009-09-09 15:08:12 +00001885 // -- If T is a template-id, its associated namespaces and classes are
1886 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001887 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001888 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001889 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001890 // namespaces in which any template template arguments are defined; and
1891 // the classes in which any member templates used as template template
1892 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001893 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001894 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001895 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1896 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1897 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001898 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001899 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001900 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Douglas Gregor69be8d62009-07-08 07:51:57 +00001902 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1903 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001904 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001905 }
Mike Stump1eb44332009-09-09 15:08:12 +00001906
John McCall86ff3082010-02-04 22:26:26 +00001907 // Only recurse into base classes for complete types.
1908 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00001909 QualType type = Result.S.Context.getTypeDeclType(Class);
1910 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
1911 /*no diagnostic*/ 0))
1912 return;
John McCall86ff3082010-02-04 22:26:26 +00001913 }
1914
Douglas Gregorfa047642009-02-04 00:32:51 +00001915 // Add direct and indirect base classes along with their associated
1916 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001917 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001918 Bases.push_back(Class);
1919 while (!Bases.empty()) {
1920 // Pop this class off the stack.
1921 Class = Bases.back();
1922 Bases.pop_back();
1923
1924 // Visit the base classes.
1925 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1926 BaseEnd = Class->bases_end();
1927 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001928 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001929 // In dependent contexts, we do ADL twice, and the first time around,
1930 // the base type might be a dependent TemplateSpecializationType, or a
1931 // TemplateTypeParmType. If that happens, simply ignore it.
1932 // FIXME: If we want to support export, we probably need to add the
1933 // namespace of the template in a TemplateSpecializationType, or even
1934 // the classes and namespaces of known non-dependent arguments.
1935 if (!BaseType)
1936 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001937 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001938 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001939 // Find the associated namespace for this base class.
1940 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001941 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001942
1943 // Make sure we visit the bases of this base class.
1944 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1945 Bases.push_back(BaseDecl);
1946 }
1947 }
1948 }
1949}
1950
1951// \brief Add the associated classes and namespaces for
1952// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001953// (C++ [basic.lookup.koenig]p2).
1954static void
John McCallc7e04da2010-05-28 18:45:08 +00001955addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001956 // C++ [basic.lookup.koenig]p2:
1957 //
1958 // For each argument type T in the function call, there is a set
1959 // of zero or more associated namespaces and a set of zero or more
1960 // associated classes to be considered. The sets of namespaces and
1961 // classes is determined entirely by the types of the function
1962 // arguments (and the namespace of any template template
1963 // argument). Typedef names and using-declarations used to specify
1964 // the types do not contribute to this set. The sets of namespaces
1965 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001966
Chris Lattner5f9e2722011-07-23 10:55:15 +00001967 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001968 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1969
Douglas Gregorfa047642009-02-04 00:32:51 +00001970 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001971 switch (T->getTypeClass()) {
1972
1973#define TYPE(Class, Base)
1974#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1975#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1976#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1977#define ABSTRACT_TYPE(Class, Base)
1978#include "clang/AST/TypeNodes.def"
1979 // T is canonical. We can also ignore dependent types because
1980 // we don't need to do ADL at the definition point, but if we
1981 // wanted to implement template export (or if we find some other
1982 // use for associated classes and namespaces...) this would be
1983 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001984 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001985
John McCallfa4edcf2010-05-28 06:08:54 +00001986 // -- If T is a pointer to U or an array of U, its associated
1987 // namespaces and classes are those associated with U.
1988 case Type::Pointer:
1989 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1990 continue;
1991 case Type::ConstantArray:
1992 case Type::IncompleteArray:
1993 case Type::VariableArray:
1994 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1995 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001996
John McCallfa4edcf2010-05-28 06:08:54 +00001997 // -- If T is a fundamental type, its associated sets of
1998 // namespaces and classes are both empty.
1999 case Type::Builtin:
2000 break;
2001
2002 // -- If T is a class type (including unions), its associated
2003 // classes are: the class itself; the class of which it is a
2004 // member, if any; and its direct and indirect base
2005 // classes. Its associated namespaces are the namespaces in
2006 // which its associated classes are defined.
2007 case Type::Record: {
2008 CXXRecordDecl *Class
2009 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002010 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00002011 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002012 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00002013
John McCallfa4edcf2010-05-28 06:08:54 +00002014 // -- If T is an enumeration type, its associated namespace is
2015 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002016 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00002017 // it has no associated class.
2018 case Type::Enum: {
2019 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002020
John McCallfa4edcf2010-05-28 06:08:54 +00002021 DeclContext *Ctx = Enum->getDeclContext();
2022 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002023 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002024
John McCallfa4edcf2010-05-28 06:08:54 +00002025 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002026 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002027
John McCallfa4edcf2010-05-28 06:08:54 +00002028 break;
2029 }
2030
2031 // -- If T is a function type, its associated namespaces and
2032 // classes are those associated with the function parameter
2033 // types and those associated with the return type.
2034 case Type::FunctionProto: {
2035 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2036 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2037 ArgEnd = Proto->arg_type_end();
2038 Arg != ArgEnd; ++Arg)
2039 Queue.push_back(Arg->getTypePtr());
2040 // fallthrough
2041 }
2042 case Type::FunctionNoProto: {
2043 const FunctionType *FnType = cast<FunctionType>(T);
2044 T = FnType->getResultType().getTypePtr();
2045 continue;
2046 }
2047
2048 // -- If T is a pointer to a member function of a class X, its
2049 // associated namespaces and classes are those associated
2050 // with the function parameter types and return type,
2051 // together with those associated with X.
2052 //
2053 // -- If T is a pointer to a data member of class X, its
2054 // associated namespaces and classes are those associated
2055 // with the member type together with those associated with
2056 // X.
2057 case Type::MemberPointer: {
2058 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2059
2060 // Queue up the class type into which this points.
2061 Queue.push_back(MemberPtr->getClass());
2062
2063 // And directly continue with the pointee type.
2064 T = MemberPtr->getPointeeType().getTypePtr();
2065 continue;
2066 }
2067
2068 // As an extension, treat this like a normal pointer.
2069 case Type::BlockPointer:
2070 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2071 continue;
2072
2073 // References aren't covered by the standard, but that's such an
2074 // obvious defect that we cover them anyway.
2075 case Type::LValueReference:
2076 case Type::RValueReference:
2077 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2078 continue;
2079
2080 // These are fundamental types.
2081 case Type::Vector:
2082 case Type::ExtVector:
2083 case Type::Complex:
2084 break;
2085
Douglas Gregorf25760e2011-04-12 01:02:45 +00002086 // If T is an Objective-C object or interface type, or a pointer to an
2087 // object or interface type, the associated namespace is the global
2088 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002089 case Type::ObjCObject:
2090 case Type::ObjCInterface:
2091 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002092 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002093 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002094
2095 // Atomic types are just wrappers; use the associations of the
2096 // contained type.
2097 case Type::Atomic:
2098 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2099 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002100 }
2101
2102 if (Queue.empty()) break;
2103 T = Queue.back();
2104 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002105 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002106}
2107
2108/// \brief Find the associated classes and namespaces for
2109/// argument-dependent lookup for a call with the given set of
2110/// arguments.
2111///
2112/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002113/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002114/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002115void
John McCall42f48fb2012-08-24 20:38:34 +00002116Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2117 llvm::ArrayRef<Expr *> Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002118 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002119 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002120 AssociatedNamespaces.clear();
2121 AssociatedClasses.clear();
2122
John McCall42f48fb2012-08-24 20:38:34 +00002123 AssociatedLookup Result(*this, InstantiationLoc,
2124 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002125
Douglas Gregorfa047642009-02-04 00:32:51 +00002126 // C++ [basic.lookup.koenig]p2:
2127 // For each argument type T in the function call, there is a set
2128 // of zero or more associated namespaces and a set of zero or more
2129 // associated classes to be considered. The sets of namespaces and
2130 // classes is determined entirely by the types of the function
2131 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002132 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002133 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002134 Expr *Arg = Args[ArgIdx];
2135
2136 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002137 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002138 continue;
2139 }
2140
2141 // [...] In addition, if the argument is the name or address of a
2142 // set of overloaded functions and/or function templates, its
2143 // associated classes and namespaces are the union of those
2144 // associated with each of the members of the set: the namespace
2145 // in which the function or function template is defined and the
2146 // classes and namespaces associated with its (non-dependent)
2147 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002148 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002149 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002150 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002151 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002152
John McCallc7e04da2010-05-28 18:45:08 +00002153 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2154 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002155
John McCallc7e04da2010-05-28 18:45:08 +00002156 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2157 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002158 // Look through any using declarations to find the underlying function.
2159 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002160
Chandler Carruthbd647292009-12-29 06:17:27 +00002161 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2162 if (!FDecl)
2163 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002164
2165 // Add the classes and namespaces associated with the parameter
2166 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002167 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002168 }
2169 }
2170}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002171
2172/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2173/// an acceptable non-member overloaded operator for a call whose
2174/// arguments have types T1 (and, if non-empty, T2). This routine
2175/// implements the check in C++ [over.match.oper]p3b2 concerning
2176/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002177static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002178IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2179 QualType T1, QualType T2,
2180 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002181 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2182 return true;
2183
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002184 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2185 return true;
2186
John McCall183700f2009-09-21 23:43:11 +00002187 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002188 if (Proto->getNumArgs() < 1)
2189 return false;
2190
2191 if (T1->isEnumeralType()) {
2192 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002193 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002194 return true;
2195 }
2196
2197 if (Proto->getNumArgs() < 2)
2198 return false;
2199
2200 if (!T2.isNull() && T2->isEnumeralType()) {
2201 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002202 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002203 return true;
2204 }
2205
2206 return false;
2207}
2208
John McCall7d384dd2009-11-18 07:57:50 +00002209NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002210 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002211 LookupNameKind NameKind,
2212 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002213 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002214 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002215 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002216}
2217
Douglas Gregor6e378de2009-04-23 23:18:26 +00002218/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002220 SourceLocation IdLoc,
2221 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002222 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002223 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002224 return cast_or_null<ObjCProtocolDecl>(D);
2225}
2226
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002227void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002228 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002229 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002230 // C++ [over.match.oper]p3:
2231 // -- The set of non-member candidates is the result of the
2232 // unqualified lookup of operator@ in the context of the
2233 // expression according to the usual rules for name lookup in
2234 // unqualified function calls (3.4.2) except that all member
2235 // functions are ignored. However, if no operand has a class
2236 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002237 // that have a first parameter of type T1 or "reference to
2238 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002239 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002240 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002241 // when T2 is an enumeration type, are candidate functions.
2242 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002243 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2244 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002246 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2247
John McCallf36e02d2009-10-09 21:13:30 +00002248 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002249 return;
2250
2251 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2252 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002253 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2254 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002255 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002256 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002257 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002258 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002259 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002260 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002261 // later?
2262 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002263 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002264 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002265 }
2266}
2267
Sean Huntc39b6bc2011-06-24 02:11:39 +00002268Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002269 CXXSpecialMember SM,
2270 bool ConstArg,
2271 bool VolatileArg,
2272 bool RValueThis,
2273 bool ConstThis,
2274 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002275 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002276 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002277 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002278 if (RValueThis || ConstThis || VolatileThis)
2279 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2280 "constructors and destructors always have unqualified lvalue this");
2281 if (ConstArg || VolatileArg)
2282 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2283 "parameter-less special members can't have qualified arguments");
2284
2285 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002286 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002287 ID.AddInteger(SM);
2288 ID.AddInteger(ConstArg);
2289 ID.AddInteger(VolatileArg);
2290 ID.AddInteger(RValueThis);
2291 ID.AddInteger(ConstThis);
2292 ID.AddInteger(VolatileThis);
2293
2294 void *InsertPoint;
2295 SpecialMemberOverloadResult *Result =
2296 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2297
2298 // This was already cached
2299 if (Result)
2300 return Result;
2301
Sean Hunt30543582011-06-07 00:11:58 +00002302 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2303 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002304 SpecialMemberCache.InsertNode(Result, InsertPoint);
2305
2306 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002307 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002308 DeclareImplicitDestructor(RD);
2309 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002310 assert(DD && "record without a destructor");
2311 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002312 Result->setKind(DD->isDeleted() ?
2313 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002314 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002315 return Result;
2316 }
2317
Sean Huntb320e0c2011-06-10 03:50:41 +00002318 // Prepare for overload resolution. Here we construct a synthetic argument
2319 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002320 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002321 DeclarationName Name;
2322 Expr *Arg = 0;
2323 unsigned NumArgs;
2324
Richard Smith704c8f72012-04-20 18:46:14 +00002325 QualType ArgType = CanTy;
2326 ExprValueKind VK = VK_LValue;
2327
Sean Huntb320e0c2011-06-10 03:50:41 +00002328 if (SM == CXXDefaultConstructor) {
2329 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2330 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002331 if (RD->needsImplicitDefaultConstructor())
2332 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002333 } else {
2334 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2335 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002336 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002337 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002338 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002339 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002340 } else {
2341 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002342 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002343 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002344 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002345 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002346 }
2347
Sean Huntb320e0c2011-06-10 03:50:41 +00002348 if (ConstArg)
2349 ArgType.addConst();
2350 if (VolatileArg)
2351 ArgType.addVolatile();
2352
2353 // This isn't /really/ specified by the standard, but it's implied
2354 // we should be working from an RValue in the case of move to ensure
2355 // that we prefer to bind to rvalue references, and an LValue in the
2356 // case of copy to ensure we don't bind to rvalue references.
2357 // Possibly an XValue is actually correct in the case of move, but
2358 // there is no semantic difference for class types in this restricted
2359 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002360 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002361 VK = VK_LValue;
2362 else
2363 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002364 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002365
Richard Smith704c8f72012-04-20 18:46:14 +00002366 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2367
2368 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002369 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002370 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002371 }
2372
2373 // Create the object argument
2374 QualType ThisTy = CanTy;
2375 if (ConstThis)
2376 ThisTy.addConst();
2377 if (VolatileThis)
2378 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002379 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002380 OpaqueValueExpr(SourceLocation(), ThisTy,
2381 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002382
2383 // Now we perform lookup on the name we computed earlier and do overload
2384 // resolution. Lookup is only performed directly into the class since there
2385 // will always be a (possibly implicit) declaration to shadow any others.
2386 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002387 DeclContext::lookup_result R = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002388
David Blaikie3bc93e32012-12-19 00:45:41 +00002389 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002390 "lookup for a constructor or assignment operator was empty");
David Blaikie3bc93e32012-12-19 00:45:41 +00002391 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002392 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002393
Sean Huntc39b6bc2011-06-24 02:11:39 +00002394 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002395 continue;
2396
Sean Huntc39b6bc2011-06-24 02:11:39 +00002397 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2398 // FIXME: [namespace.udecl]p15 says that we should only consider a
2399 // using declaration here if it does not match a declaration in the
2400 // derived class. We do not implement this correctly in other cases
2401 // either.
2402 Cand = U->getTargetDecl();
2403
2404 if (Cand->isInvalidDecl())
2405 continue;
2406 }
2407
2408 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002409 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002410 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002411 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2412 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002413 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002414 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2415 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002416 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002417 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002418 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2419 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002420 RD, 0, ThisTy, Classification,
2421 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002422 OCS, true);
2423 else
2424 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002425 0, llvm::makeArrayRef(&Arg, NumArgs),
2426 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002427 } else {
2428 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002429 }
2430 }
2431
2432 OverloadCandidateSet::iterator Best;
2433 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2434 case OR_Success:
2435 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002436 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002437 break;
2438
2439 case OR_Deleted:
2440 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002441 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002442 break;
2443
2444 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002445 Result->setMethod(0);
2446 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2447 break;
2448
Sean Huntb320e0c2011-06-10 03:50:41 +00002449 case OR_No_Viable_Function:
2450 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002451 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002452 break;
2453 }
2454
2455 return Result;
2456}
2457
2458/// \brief Look up the default constructor for the given class.
2459CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002460 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002461 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2462 false, false);
2463
2464 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002465}
2466
Sean Hunt661c67a2011-06-21 23:42:56 +00002467/// \brief Look up the copying constructor for the given class.
2468CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002469 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002470 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2471 "non-const, non-volatile qualifiers for copy ctor arg");
2472 SpecialMemberOverloadResult *Result =
2473 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2474 Quals & Qualifiers::Volatile, false, false, false);
2475
Sean Huntc530d172011-06-10 04:44:37 +00002476 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2477}
2478
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002479/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002480CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2481 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002482 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002483 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2484 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002485
2486 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2487}
2488
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002489/// \brief Look up the constructors for the given class.
2490DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002491 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002492 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002493 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002494 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002495 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002496 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002497 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002498 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002500
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002501 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2502 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2503 return Class->lookup(Name);
2504}
2505
Sean Hunt661c67a2011-06-21 23:42:56 +00002506/// \brief Look up the copying assignment operator for the given class.
2507CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2508 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002509 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002510 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2511 "non-const, non-volatile qualifiers for copy assignment arg");
2512 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2513 "non-const, non-volatile qualifiers for copy assignment this");
2514 SpecialMemberOverloadResult *Result =
2515 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2516 Quals & Qualifiers::Volatile, RValueThis,
2517 ThisQuals & Qualifiers::Const,
2518 ThisQuals & Qualifiers::Volatile);
2519
Sean Hunt661c67a2011-06-21 23:42:56 +00002520 return Result->getMethod();
2521}
2522
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002523/// \brief Look up the moving assignment operator for the given class.
2524CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002525 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002526 bool RValueThis,
2527 unsigned ThisQuals) {
2528 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2529 "non-const, non-volatile qualifiers for copy assignment this");
2530 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002531 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2532 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002533 ThisQuals & Qualifiers::Const,
2534 ThisQuals & Qualifiers::Volatile);
2535
2536 return Result->getMethod();
2537}
2538
Douglas Gregordb89f282010-07-01 22:47:18 +00002539/// \brief Look for the destructor of the given class.
2540///
Sean Huntc5c9b532011-06-03 21:10:40 +00002541/// During semantic analysis, this routine should be used in lieu of
2542/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002543///
2544/// \returns The destructor for this class.
2545CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002546 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2547 false, false, false,
2548 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002549}
2550
Richard Smith36f5cfe2012-03-09 08:00:36 +00002551/// LookupLiteralOperator - Determine which literal operator should be used for
2552/// a user-defined literal, per C++11 [lex.ext].
2553///
2554/// Normal overload resolution is not used to select which literal operator to
2555/// call for a user-defined literal. Look up the provided literal operator name,
2556/// and filter the results to the appropriate set for the given argument types.
2557Sema::LiteralOperatorLookupResult
2558Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2559 ArrayRef<QualType> ArgTys,
2560 bool AllowRawAndTemplate) {
2561 LookupName(R, S);
2562 assert(R.getResultKind() != LookupResult::Ambiguous &&
2563 "literal operator lookup can't be ambiguous");
2564
2565 // Filter the lookup results appropriately.
2566 LookupResult::Filter F = R.makeFilter();
2567
2568 bool FoundTemplate = false;
2569 bool FoundRaw = false;
2570 bool FoundExactMatch = false;
2571
2572 while (F.hasNext()) {
2573 Decl *D = F.next();
2574 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2575 D = USD->getTargetDecl();
2576
2577 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2578 bool IsRaw = false;
2579 bool IsExactMatch = false;
2580
2581 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2582 if (FD->getNumParams() == 1 &&
2583 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2584 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002585 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002586 IsExactMatch = true;
2587 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2588 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2589 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2590 IsExactMatch = false;
2591 break;
2592 }
2593 }
2594 }
2595 }
2596
2597 if (IsExactMatch) {
2598 FoundExactMatch = true;
2599 AllowRawAndTemplate = false;
2600 if (FoundRaw || FoundTemplate) {
2601 // Go through again and remove the raw and template decls we've
2602 // already found.
2603 F.restart();
2604 FoundRaw = FoundTemplate = false;
2605 }
2606 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2607 FoundTemplate |= IsTemplate;
2608 FoundRaw |= IsRaw;
2609 } else {
2610 F.erase();
2611 }
2612 }
2613
2614 F.done();
2615
2616 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2617 // parameter type, that is used in preference to a raw literal operator
2618 // or literal operator template.
2619 if (FoundExactMatch)
2620 return LOLR_Cooked;
2621
2622 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2623 // operator template, but not both.
2624 if (FoundRaw && FoundTemplate) {
2625 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2626 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2627 Decl *D = *I;
2628 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2629 D = USD->getTargetDecl();
2630 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2631 D = FunTmpl->getTemplatedDecl();
2632 NoteOverloadCandidate(cast<FunctionDecl>(D));
2633 }
2634 return LOLR_Error;
2635 }
2636
2637 if (FoundRaw)
2638 return LOLR_Raw;
2639
2640 if (FoundTemplate)
2641 return LOLR_Template;
2642
2643 // Didn't find anything we could use.
2644 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2645 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2646 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2647 return LOLR_Error;
2648}
2649
John McCall7edb5fd2010-01-26 07:16:45 +00002650void ADLResult::insert(NamedDecl *New) {
2651 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2652
2653 // If we haven't yet seen a decl for this key, or the last decl
2654 // was exactly this one, we're done.
2655 if (Old == 0 || Old == New) {
2656 Old = New;
2657 return;
2658 }
2659
2660 // Otherwise, decide which is a more recent redeclaration.
2661 FunctionDecl *OldFD, *NewFD;
2662 if (isa<FunctionTemplateDecl>(New)) {
2663 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2664 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2665 } else {
2666 OldFD = cast<FunctionDecl>(Old);
2667 NewFD = cast<FunctionDecl>(New);
2668 }
2669
2670 FunctionDecl *Cursor = NewFD;
2671 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002672 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002673
2674 // If we got to the end without finding OldFD, OldFD is the newer
2675 // declaration; leave things as they are.
2676 if (!Cursor) return;
2677
2678 // If we do find OldFD, then NewFD is newer.
2679 if (Cursor == OldFD) break;
2680
2681 // Otherwise, keep looking.
2682 }
2683
2684 Old = New;
2685}
2686
Sebastian Redl644be852009-10-23 19:23:15 +00002687void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00002688 SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002689 llvm::ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002690 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002691 // Find all of the associated namespaces and classes based on the
2692 // arguments we have.
2693 AssociatedNamespaceSet AssociatedNamespaces;
2694 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002695 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002696 AssociatedNamespaces,
2697 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002698
Sebastian Redl644be852009-10-23 19:23:15 +00002699 QualType T1, T2;
2700 if (Operator) {
2701 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002702 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002703 T2 = Args[1]->getType();
2704 }
2705
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002706 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002707 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2708 // and let Y be the lookup set produced by argument dependent
2709 // lookup (defined as follows). If X contains [...] then Y is
2710 // empty. Otherwise Y is the set of declarations found in the
2711 // namespaces associated with the argument types as described
2712 // below. The set of declarations found by the lookup of the name
2713 // is the union of X and Y.
2714 //
2715 // Here, we compute Y and add its members to the overloaded
2716 // candidate set.
2717 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002718 NSEnd = AssociatedNamespaces.end();
2719 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002720 // When considering an associated namespace, the lookup is the
2721 // same as the lookup performed when the associated namespace is
2722 // used as a qualifier (3.4.3.2) except that:
2723 //
2724 // -- Any using-directives in the associated namespace are
2725 // ignored.
2726 //
John McCall6ff07852009-08-07 22:18:02 +00002727 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002728 // associated classes are visible within their respective
2729 // namespaces even if they are not visible during an ordinary
2730 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002731 DeclContext::lookup_result R = (*NS)->lookup(Name);
2732 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2733 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002734 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002735 // If the only declaration here is an ordinary friend, consider
2736 // it only if it was declared in an associated classes.
2737 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002738 DeclContext *LexDC = D->getLexicalDeclContext();
2739 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2740 continue;
2741 }
Mike Stump1eb44332009-09-09 15:08:12 +00002742
John McCalla113e722010-01-26 06:04:06 +00002743 if (isa<UsingShadowDecl>(D))
2744 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002745
John McCalla113e722010-01-26 06:04:06 +00002746 if (isa<FunctionDecl>(D)) {
2747 if (Operator &&
2748 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2749 T1, T2, Context))
2750 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002751 } else if (!isa<FunctionTemplateDecl>(D))
2752 continue;
2753
2754 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002755 }
2756 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002757}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002758
2759//----------------------------------------------------------------------------
2760// Search for all visible declarations.
2761//----------------------------------------------------------------------------
2762VisibleDeclConsumer::~VisibleDeclConsumer() { }
2763
2764namespace {
2765
2766class ShadowContextRAII;
2767
2768class VisibleDeclsRecord {
2769public:
2770 /// \brief An entry in the shadow map, which is optimized to store a
2771 /// single declaration (the common case) but can also store a list
2772 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002773 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002774
2775private:
2776 /// \brief A mapping from declaration names to the declarations that have
2777 /// this name within a particular scope.
2778 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2779
2780 /// \brief A list of shadow maps, which is used to model name hiding.
2781 std::list<ShadowMap> ShadowMaps;
2782
2783 /// \brief The declaration contexts we have already visited.
2784 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2785
2786 friend class ShadowContextRAII;
2787
2788public:
2789 /// \brief Determine whether we have already visited this context
2790 /// (and, if not, note that we are going to visit that context now).
2791 bool visitedContext(DeclContext *Ctx) {
2792 return !VisitedContexts.insert(Ctx);
2793 }
2794
Douglas Gregor8071e422010-08-15 06:18:01 +00002795 bool alreadyVisitedContext(DeclContext *Ctx) {
2796 return VisitedContexts.count(Ctx);
2797 }
2798
Douglas Gregor546be3c2009-12-30 17:04:44 +00002799 /// \brief Determine whether the given declaration is hidden in the
2800 /// current scope.
2801 ///
2802 /// \returns the declaration that hides the given declaration, or
2803 /// NULL if no such declaration exists.
2804 NamedDecl *checkHidden(NamedDecl *ND);
2805
2806 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002807 void add(NamedDecl *ND) {
2808 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2809 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002810};
2811
2812/// \brief RAII object that records when we've entered a shadow context.
2813class ShadowContextRAII {
2814 VisibleDeclsRecord &Visible;
2815
2816 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2817
2818public:
2819 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2820 Visible.ShadowMaps.push_back(ShadowMap());
2821 }
2822
2823 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002824 Visible.ShadowMaps.pop_back();
2825 }
2826};
2827
2828} // end anonymous namespace
2829
Douglas Gregor546be3c2009-12-30 17:04:44 +00002830NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002831 // Look through using declarations.
2832 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002833
Douglas Gregor546be3c2009-12-30 17:04:44 +00002834 unsigned IDNS = ND->getIdentifierNamespace();
2835 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2836 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2837 SM != SMEnd; ++SM) {
2838 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2839 if (Pos == SM->end())
2840 continue;
2841
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002842 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002843 IEnd = Pos->second.end();
2844 I != IEnd; ++I) {
2845 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002846 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002847 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002848 Decl::IDNS_ObjCProtocol)))
2849 continue;
2850
2851 // Protocols are in distinct namespaces from everything else.
2852 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2853 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2854 (*I)->getIdentifierNamespace() != IDNS)
2855 continue;
2856
Douglas Gregor0cc84042010-01-14 15:47:35 +00002857 // Functions and function templates in the same scope overload
2858 // rather than hide. FIXME: Look for hiding based on function
2859 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002860 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002861 ND->isFunctionOrFunctionTemplate() &&
2862 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002863 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002864
Douglas Gregor546be3c2009-12-30 17:04:44 +00002865 // We've found a declaration that hides this one.
2866 return *I;
2867 }
2868 }
2869
2870 return 0;
2871}
2872
2873static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2874 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002875 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002876 VisibleDeclConsumer &Consumer,
2877 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002878 if (!Ctx)
2879 return;
2880
Douglas Gregor546be3c2009-12-30 17:04:44 +00002881 // Make sure we don't visit the same context twice.
2882 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2883 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002884
Douglas Gregor4923aa22010-07-02 20:37:36 +00002885 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2886 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2887
Douglas Gregor546be3c2009-12-30 17:04:44 +00002888 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00002889 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2890 LEnd = Ctx->lookups_end();
2891 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002892 DeclContext::lookup_result R = *L;
2893 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2894 ++I) {
2895 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00002896 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002897 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002898 Visited.add(ND);
2899 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002900 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002901 }
2902 }
2903
2904 // Traverse using directives for qualified name lookup.
2905 if (QualifiedNameLookup) {
2906 ShadowContextRAII Shadow(Visited);
2907 DeclContext::udir_iterator I, E;
2908 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002909 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002910 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002911 }
2912 }
2913
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002914 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002915 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002916 if (!Record->hasDefinition())
2917 return;
2918
Douglas Gregor546be3c2009-12-30 17:04:44 +00002919 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2920 BEnd = Record->bases_end();
2921 B != BEnd; ++B) {
2922 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002923
Douglas Gregor546be3c2009-12-30 17:04:44 +00002924 // Don't look into dependent bases, because name lookup can't look
2925 // there anyway.
2926 if (BaseType->isDependentType())
2927 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002928
Douglas Gregor546be3c2009-12-30 17:04:44 +00002929 const RecordType *Record = BaseType->getAs<RecordType>();
2930 if (!Record)
2931 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002932
Douglas Gregor546be3c2009-12-30 17:04:44 +00002933 // FIXME: It would be nice to be able to determine whether referencing
2934 // a particular member would be ambiguous. For example, given
2935 //
2936 // struct A { int member; };
2937 // struct B { int member; };
2938 // struct C : A, B { };
2939 //
2940 // void f(C *c) { c->### }
2941 //
2942 // accessing 'member' would result in an ambiguity. However, we
2943 // could be smart enough to qualify the member with the base
2944 // class, e.g.,
2945 //
2946 // c->B::member
2947 //
2948 // or
2949 //
2950 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002951
Douglas Gregor546be3c2009-12-30 17:04:44 +00002952 // Find results in this base class (and its bases).
2953 ShadowContextRAII Shadow(Visited);
2954 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002955 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002956 }
2957 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002958
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002959 // Traverse the contexts of Objective-C classes.
2960 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2961 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00002962 for (ObjCInterfaceDecl::visible_categories_iterator
2963 Cat = IFace->visible_categories_begin(),
2964 CatEnd = IFace->visible_categories_end();
2965 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002966 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00002967 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002968 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002969 }
2970
2971 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002972 for (ObjCInterfaceDecl::all_protocol_iterator
2973 I = IFace->all_referenced_protocol_begin(),
2974 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002975 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002976 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002977 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002978 }
2979
2980 // Traverse the superclass.
2981 if (IFace->getSuperClass()) {
2982 ShadowContextRAII Shadow(Visited);
2983 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002984 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002985 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002986
Douglas Gregorc220a182010-04-19 18:02:19 +00002987 // If there is an implementation, traverse it. We do this to find
2988 // synthesized ivars.
2989 if (IFace->getImplementation()) {
2990 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002991 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00002992 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00002993 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002994 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2995 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2996 E = Protocol->protocol_end(); I != E; ++I) {
2997 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002998 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002999 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003000 }
3001 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3002 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3003 E = Category->protocol_end(); I != E; ++I) {
3004 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003005 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003006 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003007 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003008
Douglas Gregorc220a182010-04-19 18:02:19 +00003009 // If there is an implementation, traverse it.
3010 if (Category->getImplementation()) {
3011 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003012 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00003013 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003014 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003015 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003016}
3017
3018static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3019 UnqualUsingDirectiveSet &UDirs,
3020 VisibleDeclConsumer &Consumer,
3021 VisibleDeclsRecord &Visited) {
3022 if (!S)
3023 return;
3024
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003025 if (!S->getEntity() ||
3026 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00003027 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00003028 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3029 // Walk through the declarations in this Scope.
3030 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3031 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003032 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003033 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003034 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003035 Visited.add(ND);
3036 }
3037 }
3038 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003039
Douglas Gregor711be1e2010-03-15 14:33:29 +00003040 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003041 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003042 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003043 // Look into this scope's declaration context, along with any of its
3044 // parent lookup contexts (e.g., enclosing classes), up to the point
3045 // where we hit the context stored in the next outer scope.
3046 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003047 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003048
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003049 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003050 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003051 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3052 if (Method->isInstanceMethod()) {
3053 // For instance methods, look for ivars in the method's interface.
3054 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3055 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003056 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003057 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00003058 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003059 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003060 }
3061
3062 // We've already performed all of the name lookup that we need
3063 // to for Objective-C methods; the next context will be the
3064 // outer scope.
3065 break;
3066 }
3067
Douglas Gregor546be3c2009-12-30 17:04:44 +00003068 if (Ctx->isFunctionOrMethod())
3069 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003070
3071 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003072 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003073 }
3074 } else if (!S->getParent()) {
3075 // Look into the translation unit scope. We walk through the translation
3076 // unit's declaration context, because the Scope itself won't have all of
3077 // the declarations if we loaded a precompiled header.
3078 // FIXME: We would like the translation unit's Scope object to point to the
3079 // translation unit, so we don't need this special "if" branch. However,
3080 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003081 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003082 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003083 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003084 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003085 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003086 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003087 }
3088
Douglas Gregor546be3c2009-12-30 17:04:44 +00003089 if (Entity) {
3090 // Lookup visible declarations in any namespaces found by using
3091 // directives.
3092 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3093 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3094 for (; UI != UEnd; ++UI)
3095 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003096 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003097 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003098 }
3099
3100 // Lookup names in the parent scope.
3101 ShadowContextRAII Shadow(Visited);
3102 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3103}
3104
3105void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003106 VisibleDeclConsumer &Consumer,
3107 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003108 // Determine the set of using directives available during
3109 // unqualified name lookup.
3110 Scope *Initial = S;
3111 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003112 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003113 // Find the first namespace or translation-unit scope.
3114 while (S && !isNamespaceOrTranslationUnitScope(S))
3115 S = S->getParent();
3116
3117 UDirs.visitScopeChain(Initial, S);
3118 }
3119 UDirs.done();
3120
3121 // Look for visible declarations.
3122 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3123 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003124 if (!IncludeGlobalScope)
3125 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003126 ShadowContextRAII Shadow(Visited);
3127 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3128}
3129
3130void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003131 VisibleDeclConsumer &Consumer,
3132 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003133 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3134 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003135 if (!IncludeGlobalScope)
3136 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003137 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003138 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003139 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003140}
3141
Chris Lattner4ae493c2011-02-18 02:08:43 +00003142/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003143/// If GnuLabelLoc is a valid source location, then this is a definition
3144/// of an __label__ label name, otherwise it is a normal label definition
3145/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003146LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003147 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003148 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003149 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003150
3151 if (GnuLabelLoc.isValid()) {
3152 // Local label definitions always shadow existing labels.
3153 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3154 Scope *S = CurScope;
3155 PushOnScopeChains(Res, S, true);
3156 return cast<LabelDecl>(Res);
3157 }
3158
3159 // Not a GNU local label.
3160 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3161 // If we found a label, check to see if it is in the same context as us.
3162 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003163 if (Res && Res->getDeclContext() != CurContext)
3164 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003165 if (Res == 0) {
3166 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003167 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3168 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003169 assert(S && "Not in a function?");
3170 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003171 }
Chris Lattner337e5502011-02-18 01:27:55 +00003172 return cast<LabelDecl>(Res);
3173}
3174
3175//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003176// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003177//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003178
3179namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003180
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003181typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003182typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003183typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003184
3185static const unsigned MaxTypoDistanceResultSets = 5;
3186
Douglas Gregor546be3c2009-12-30 17:04:44 +00003187class TypoCorrectionConsumer : public VisibleDeclConsumer {
3188 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003189 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003190
3191 /// \brief The results found that have the smallest edit distance
3192 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003193 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003194 /// The pointer value being set to the current DeclContext indicates
3195 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003196 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003197
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003198 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199
Douglas Gregor546be3c2009-12-30 17:04:44 +00003200public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003201 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003203 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003204
Erik Verbruggend1205962011-10-06 07:27:49 +00003205 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3206 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003207 void FoundName(StringRef Name);
3208 void addKeywordResult(StringRef Keyword);
3209 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003210 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003211 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003212
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003213 typedef TypoResultsMap::iterator result_iterator;
3214 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003215 distance_iterator begin() { return CorrectionResults.begin(); }
3216 distance_iterator end() { return CorrectionResults.end(); }
3217 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3218 unsigned size() const { return CorrectionResults.size(); }
3219 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003220
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003221 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003222 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003223 }
3224
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003225 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003226 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003227 return (std::numeric_limits<unsigned>::max)();
3228
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003229 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003230 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003231 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003232
3233 TypoResultsMap &getBestResults() {
3234 return CorrectionResults.begin()->second;
3235 }
3236
Douglas Gregor546be3c2009-12-30 17:04:44 +00003237};
3238
3239}
3240
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003242 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003243 // Don't consider hidden names for typo correction.
3244 if (Hiding)
3245 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003246
Douglas Gregor546be3c2009-12-30 17:04:44 +00003247 // Only consider entities with identifiers for names, ignoring
3248 // special names (constructors, overloaded operators, selectors,
3249 // etc.).
3250 IdentifierInfo *Name = ND->getIdentifier();
3251 if (!Name)
3252 return;
3253
Douglas Gregor95f42922010-10-14 22:11:03 +00003254 FoundName(Name->getName());
3255}
3256
Chris Lattner5f9e2722011-07-23 10:55:15 +00003257void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003258 // Use a simple length-based heuristic to determine the minimum possible
3259 // edit distance. If the minimum isn't good enough, bail out early.
3260 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003261 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003262 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263
Douglas Gregora1194772010-10-19 22:14:33 +00003264 // Compute an upper bound on the allowable edit distance, so that the
3265 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003266 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003267
Douglas Gregor546be3c2009-12-30 17:04:44 +00003268 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003269 // entity, and add the identifier to the list of results.
3270 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003271}
3272
Chris Lattner5f9e2722011-07-23 10:55:15 +00003273void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003274 // Compute the edit distance between the typo and this keyword,
3275 // and add the keyword to the list of results.
3276 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003277}
3278
Chris Lattner5f9e2722011-07-23 10:55:15 +00003279void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003280 NamedDecl *ND,
3281 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003282 NestedNameSpecifier *NNS,
3283 bool isKeyword) {
3284 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3285 if (isKeyword) TC.makeKeyword();
3286 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003287}
3288
3289void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003290 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003291 TypoResultList &CList =
3292 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003293
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003294 if (!CList.empty() && !CList.back().isResolved())
3295 CList.pop_back();
3296 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3297 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3298 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3299 RI != RIEnd; ++RI) {
3300 // If the Correction refers to a decl already in the result list,
3301 // replace the existing result if the string representation of Correction
3302 // comes before the current result alphabetically, then stop as there is
3303 // nothing more to be done to add Correction to the candidate set.
3304 if (RI->getCorrectionDecl() == NewND) {
3305 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3306 *RI = Correction;
3307 return;
3308 }
3309 }
3310 }
3311 if (CList.empty() || Correction.isResolved())
3312 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003313
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003314 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3315 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003316}
3317
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003318// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3319// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3320// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3321static void getNestedNameSpecifierIdentifiers(
3322 NestedNameSpecifier *NNS,
3323 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3324 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3325 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3326 else
3327 Identifiers.clear();
3328
3329 const IdentifierInfo *II = NULL;
3330
3331 switch (NNS->getKind()) {
3332 case NestedNameSpecifier::Identifier:
3333 II = NNS->getAsIdentifier();
3334 break;
3335
3336 case NestedNameSpecifier::Namespace:
3337 if (NNS->getAsNamespace()->isAnonymousNamespace())
3338 return;
3339 II = NNS->getAsNamespace()->getIdentifier();
3340 break;
3341
3342 case NestedNameSpecifier::NamespaceAlias:
3343 II = NNS->getAsNamespaceAlias()->getIdentifier();
3344 break;
3345
3346 case NestedNameSpecifier::TypeSpecWithTemplate:
3347 case NestedNameSpecifier::TypeSpec:
3348 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3349 break;
3350
3351 case NestedNameSpecifier::Global:
3352 return;
3353 }
3354
3355 if (II)
3356 Identifiers.push_back(II);
3357}
3358
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003359namespace {
3360
3361class SpecifierInfo {
3362 public:
3363 DeclContext* DeclCtx;
3364 NestedNameSpecifier* NameSpecifier;
3365 unsigned EditDistance;
3366
3367 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3368 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3369};
3370
Chris Lattner5f9e2722011-07-23 10:55:15 +00003371typedef SmallVector<DeclContext*, 4> DeclContextList;
3372typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003373
3374class NamespaceSpecifierSet {
3375 ASTContext &Context;
3376 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003377 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3378 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003379 bool isSorted;
3380
3381 SpecifierInfoList Specifiers;
3382 llvm::SmallSetVector<unsigned, 4> Distances;
3383 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3384
3385 /// \brief Helper for building the list of DeclContexts between the current
3386 /// context and the top of the translation unit
3387 static DeclContextList BuildContextChain(DeclContext *Start);
3388
3389 void SortNamespaces();
3390
3391 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003392 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3393 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003394 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003395 isSorted(true) {
3396 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3397 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3398 CurNameSpecifierIdentifiers);
3399 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003400 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003401 // context.
3402 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3403 CEnd = CurContextChain.rend();
3404 C != CEnd; ++C) {
3405 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3406 CurContextIdentifiers.push_back(ND->getIdentifier());
3407 }
3408 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003409
3410 /// \brief Add the namespace to the set, computing the corresponding
3411 /// NestedNameSpecifier and its distance in the process.
3412 void AddNamespace(NamespaceDecl *ND);
3413
3414 typedef SpecifierInfoList::iterator iterator;
3415 iterator begin() {
3416 if (!isSorted) SortNamespaces();
3417 return Specifiers.begin();
3418 }
3419 iterator end() { return Specifiers.end(); }
3420};
3421
3422}
3423
3424DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0db9d202013-04-08 21:55:21 +00003425 assert(Start && "Building a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003426 DeclContextList Chain;
3427 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3428 DC = DC->getLookupParent()) {
3429 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3430 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3431 !(ND && ND->isAnonymousNamespace()))
3432 Chain.push_back(DC->getPrimaryContext());
3433 }
3434 return Chain;
3435}
3436
3437void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003438 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003439 sortedDistances.append(Distances.begin(), Distances.end());
3440
3441 if (sortedDistances.size() > 1)
3442 std::sort(sortedDistances.begin(), sortedDistances.end());
3443
3444 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003445 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003446 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003447 DI != DIEnd; ++DI) {
3448 SpecifierInfoList &SpecList = DistanceMap[*DI];
3449 Specifiers.append(SpecList.begin(), SpecList.end());
3450 }
3451
3452 isSorted = true;
3453}
3454
3455void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003456 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003457 NestedNameSpecifier *NNS = NULL;
3458 unsigned NumSpecifiers = 0;
3459 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003460 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003461
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003462 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003463 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3464 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003465 C != CEnd && !NamespaceDeclChain.empty() &&
3466 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003467 NamespaceDeclChain.pop_back();
3468 }
3469
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003470 // Add an explicit leading '::' specifier if needed.
3471 if (NamespaceDecl *ND =
Kaelyn Uhrain3ad02aa2012-02-15 22:59:03 +00003472 NamespaceDeclChain.empty() ? NULL :
3473 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003474 IdentifierInfo *Name = ND->getIdentifier();
3475 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3476 Name) != CurContextIdentifiers.end() ||
3477 std::find(CurNameSpecifierIdentifiers.begin(),
3478 CurNameSpecifierIdentifiers.end(),
3479 Name) != CurNameSpecifierIdentifiers.end()) {
3480 NamespaceDeclChain = FullNamespaceDeclChain;
3481 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3482 }
3483 }
3484
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003485 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3486 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3487 CEnd = NamespaceDeclChain.rend();
3488 C != CEnd; ++C) {
3489 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3490 if (ND) {
3491 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3492 ++NumSpecifiers;
3493 }
3494 }
3495
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003496 // If the built NestedNameSpecifier would be replacing an existing
3497 // NestedNameSpecifier, use the number of component identifiers that
3498 // would need to be changed as the edit distance instead of the number
3499 // of components in the built NestedNameSpecifier.
3500 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3501 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3502 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3503 NumSpecifiers = llvm::ComputeEditDistance(
3504 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3505 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3506 }
3507
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003508 isSorted = false;
3509 Distances.insert(NumSpecifiers);
3510 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003511}
3512
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003513/// \brief Perform name lookup for a possible result for typo correction.
3514static void LookupPotentialTypoResult(Sema &SemaRef,
3515 LookupResult &Res,
3516 IdentifierInfo *Name,
3517 Scope *S, CXXScopeSpec *SS,
3518 DeclContext *MemberContext,
3519 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003520 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003521 Res.suppressDiagnostics();
3522 Res.clear();
3523 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003524 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003525 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003526 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003527 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3528 Res.addDecl(Ivar);
3529 Res.resolveKind();
3530 return;
3531 }
3532 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003533
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003534 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3535 Res.addDecl(Prop);
3536 Res.resolveKind();
3537 return;
3538 }
3539 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003540
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003541 SemaRef.LookupQualifiedName(Res, MemberContext);
3542 return;
3543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003544
3545 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003546 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003547
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003548 // Fake ivar lookup; this should really be part of
3549 // LookupParsedName.
3550 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3551 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003552 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003553 (Res.isSingleResult() &&
3554 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003555 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003556 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3557 Res.addDecl(IV);
3558 Res.resolveKind();
3559 }
3560 }
3561 }
3562}
3563
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003564/// \brief Add keywords to the consumer as possible typo corrections.
3565static void AddKeywordsToConsumer(Sema &SemaRef,
3566 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003567 Scope *S, CorrectionCandidateCallback &CCC,
3568 bool AfterNestedNameSpecifier) {
3569 if (AfterNestedNameSpecifier) {
3570 // For 'X::', we know exactly which keywords can appear next.
3571 Consumer.addKeywordResult("template");
3572 if (CCC.WantExpressionKeywords)
3573 Consumer.addKeywordResult("operator");
3574 return;
3575 }
3576
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003577 if (CCC.WantObjCSuper)
3578 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003579
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003580 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003581 // Add type-specifier keywords to the set of results.
3582 const char *CTypeSpecs[] = {
3583 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003584 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003585 "_Complex", "_Imaginary",
3586 // storage-specifiers as well
3587 "extern", "inline", "static", "typedef"
3588 };
3589
3590 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3591 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3592 Consumer.addKeywordResult(CTypeSpecs[I]);
3593
David Blaikie4e4d0842012-03-11 07:00:24 +00003594 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003595 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003596 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003597 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003598 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003599 Consumer.addKeywordResult("_Bool");
3600
David Blaikie4e4d0842012-03-11 07:00:24 +00003601 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003602 Consumer.addKeywordResult("class");
3603 Consumer.addKeywordResult("typename");
3604 Consumer.addKeywordResult("wchar_t");
3605
Richard Smith80ad52f2013-01-02 11:42:31 +00003606 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003607 Consumer.addKeywordResult("char16_t");
3608 Consumer.addKeywordResult("char32_t");
3609 Consumer.addKeywordResult("constexpr");
3610 Consumer.addKeywordResult("decltype");
3611 Consumer.addKeywordResult("thread_local");
3612 }
3613 }
3614
David Blaikie4e4d0842012-03-11 07:00:24 +00003615 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003616 Consumer.addKeywordResult("typeof");
3617 }
3618
David Blaikie4e4d0842012-03-11 07:00:24 +00003619 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003620 Consumer.addKeywordResult("const_cast");
3621 Consumer.addKeywordResult("dynamic_cast");
3622 Consumer.addKeywordResult("reinterpret_cast");
3623 Consumer.addKeywordResult("static_cast");
3624 }
3625
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003626 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003627 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003628 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003629 Consumer.addKeywordResult("false");
3630 Consumer.addKeywordResult("true");
3631 }
3632
David Blaikie4e4d0842012-03-11 07:00:24 +00003633 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003634 const char *CXXExprs[] = {
3635 "delete", "new", "operator", "throw", "typeid"
3636 };
3637 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3638 for (unsigned I = 0; I != NumCXXExprs; ++I)
3639 Consumer.addKeywordResult(CXXExprs[I]);
3640
3641 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3642 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3643 Consumer.addKeywordResult("this");
3644
Richard Smith80ad52f2013-01-02 11:42:31 +00003645 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003646 Consumer.addKeywordResult("alignof");
3647 Consumer.addKeywordResult("nullptr");
3648 }
3649 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003650
3651 if (SemaRef.getLangOpts().C11) {
3652 // FIXME: We should not suggest _Alignof if the alignof macro
3653 // is present.
3654 Consumer.addKeywordResult("_Alignof");
3655 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003656 }
3657
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003658 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003659 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3660 // Statements.
3661 const char *CStmts[] = {
3662 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3663 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3664 for (unsigned I = 0; I != NumCStmts; ++I)
3665 Consumer.addKeywordResult(CStmts[I]);
3666
David Blaikie4e4d0842012-03-11 07:00:24 +00003667 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003668 Consumer.addKeywordResult("catch");
3669 Consumer.addKeywordResult("try");
3670 }
3671
3672 if (S && S->getBreakParent())
3673 Consumer.addKeywordResult("break");
3674
3675 if (S && S->getContinueParent())
3676 Consumer.addKeywordResult("continue");
3677
3678 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3679 Consumer.addKeywordResult("case");
3680 Consumer.addKeywordResult("default");
3681 }
3682 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003683 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003684 Consumer.addKeywordResult("namespace");
3685 Consumer.addKeywordResult("template");
3686 }
3687
3688 if (S && S->isClassScope()) {
3689 Consumer.addKeywordResult("explicit");
3690 Consumer.addKeywordResult("friend");
3691 Consumer.addKeywordResult("mutable");
3692 Consumer.addKeywordResult("private");
3693 Consumer.addKeywordResult("protected");
3694 Consumer.addKeywordResult("public");
3695 Consumer.addKeywordResult("virtual");
3696 }
3697 }
3698
David Blaikie4e4d0842012-03-11 07:00:24 +00003699 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003700 Consumer.addKeywordResult("using");
3701
Richard Smith80ad52f2013-01-02 11:42:31 +00003702 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003703 Consumer.addKeywordResult("static_assert");
3704 }
3705 }
3706}
3707
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003708static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3709 TypoCorrection &Candidate) {
3710 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3711 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3712}
3713
Douglas Gregor546be3c2009-12-30 17:04:44 +00003714/// \brief Try to "correct" a typo in the source code by finding
3715/// visible declarations whose names are similar to the name that was
3716/// present in the source code.
3717///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003718/// \param TypoName the \c DeclarationNameInfo structure that contains
3719/// the name that was present in the source code along with its location.
3720///
3721/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003722///
3723/// \param S the scope in which name lookup occurs.
3724///
3725/// \param SS the nested-name-specifier that precedes the name we're
3726/// looking for, if present.
3727///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003728/// \param CCC A CorrectionCandidateCallback object that provides further
3729/// validation of typo correction candidates. It also provides flags for
3730/// determining the set of keywords permitted.
3731///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003732/// \param MemberContext if non-NULL, the context in which to look for
3733/// a member access expression.
3734///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003735/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003736/// the nested-name-specifier SS.
3737///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003738/// \param OPT when non-NULL, the search for visible declarations will
3739/// also walk the protocols in the qualified interfaces of \p OPT.
3740///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003741/// \returns a \c TypoCorrection containing the corrected name if the typo
3742/// along with information such as the \c NamedDecl where the corrected name
3743/// was declared, and any additional \c NestedNameSpecifier needed to access
3744/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3745TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3746 Sema::LookupNameKind LookupKind,
3747 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003748 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003749 DeclContext *MemberContext,
3750 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003751 const ObjCObjectPointerType *OPT) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003752 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003753 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003754
Francois Pichet4d604d62011-12-03 15:55:29 +00003755 // In Microsoft mode, don't perform typo correction in a template member
3756 // function dependent context because it interferes with the "lookup into
3757 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003758 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003759 isa<CXXMethodDecl>(CurContext))
3760 return TypoCorrection();
3761
Douglas Gregor546be3c2009-12-30 17:04:44 +00003762 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003763 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003764 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003765 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003766
3767 // If the scope specifier itself was invalid, don't try to correct
3768 // typos.
3769 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003770 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003771
3772 // Never try to correct typos during template deduction or
3773 // instantiation.
3774 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003775 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003776
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003777 // Don't try to correct 'super'.
3778 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3779 return TypoCorrection();
3780
Argyrios Kyrtzidis6aa240c2013-03-16 01:40:35 +00003781 // This is for testing.
3782 if (Diags.getWarnOnSpellCheck()) {
3783 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
3784 "spell-checking initiated for %0");
3785 Diag(TypoName.getLoc(), DiagID) << TypoName.getName();
3786 }
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003787
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003788 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003789
3790 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003791
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003792 // If a callback object considers an empty typo correction candidate to be
3793 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003794 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003795 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003796
Douglas Gregoraaf87162010-04-14 20:04:41 +00003797 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003798 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003799 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003800 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003801 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003802
3803 // Look in qualified interfaces.
3804 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003805 for (ObjCObjectPointerType::qual_iterator
3806 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003807 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003808 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003809 }
3810 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003811 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3812 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003813 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003815 // Provide a stop gap for files that are just seriously broken. Trying
3816 // to correct all typos can turn into a HUGE performance penalty, causing
3817 // some files to take minutes to get rejected by the parser.
3818 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003819 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003820 ++TyposCorrected;
3821
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003822 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003823 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003824 IsUnqualifiedLookup = true;
3825 UnqualifiedTyposCorrectedMap::iterator Cached
3826 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003827 if (Cached != UnqualifiedTyposCorrected.end()) {
3828 // Add the cached value, unless it's a keyword or fails validation. In the
3829 // keyword case, we'll end up adding the keyword below.
3830 if (Cached->second) {
3831 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003832 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003833 Consumer.addCorrection(Cached->second);
3834 } else {
3835 // Only honor no-correction cache hits when a callback that will validate
3836 // correction candidates is not being used.
3837 if (!ValidatingCallback)
3838 return TypoCorrection();
3839 }
3840 }
3841 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003842 // Provide a stop gap for files that are just seriously broken. Trying
3843 // to correct all typos can turn into a HUGE performance penalty, causing
3844 // some files to take minutes to get rejected by the parser.
3845 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003846 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003847 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003848 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003849
Douglas Gregor01798682012-03-26 16:54:18 +00003850 // Determine whether we are going to search in the various namespaces for
3851 // corrections.
3852 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00003853 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00003854 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003855 // In a few cases we *only* want to search for corrections bases on just
3856 // adding or changing the nested name specifier.
3857 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00003858
3859 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003860 // For unqualified lookup, look through all of the names that we have
3861 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003862 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003863 for (IdentifierTable::iterator I = Context.Idents.begin(),
3864 IEnd = Context.Idents.end();
3865 I != IEnd; ++I)
3866 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003867
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003868 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003869 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003870 if (IdentifierInfoLookup *External
3871 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003872 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003873 do {
3874 StringRef Name = Iter->Next();
3875 if (Name.empty())
3876 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003877
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003878 Consumer.FoundName(Name);
3879 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00003880 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003881 }
3882
Richard Smith0f4b5be2012-06-08 21:35:42 +00003883 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003884
Douglas Gregoraaf87162010-04-14 20:04:41 +00003885 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003886 if (Consumer.empty()) {
3887 // If this was an unqualified lookup, note that no correction was found.
3888 if (IsUnqualifiedLookup)
3889 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003890
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003891 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003892 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003893
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003894 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3895 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003896 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003897 if (ED > 0 && Typo->getName().size() / ED < 3) {
3898 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003899 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003900 (void)UnqualifiedTyposCorrected[Typo];
3901
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003902 return TypoCorrection();
3903 }
3904
Douglas Gregor01798682012-03-26 16:54:18 +00003905 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3906 // to search those namespaces.
3907 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003908 // Load any externally-known namespaces.
3909 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003910 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003911 LoadedExternalKnownNamespaces = true;
3912 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3913 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3914 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3915 }
3916
Nick Lewycky01a41142013-01-26 00:35:08 +00003917 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003918 KNI = KnownNamespaces.begin(),
3919 KNIEnd = KnownNamespaces.end();
3920 KNI != KNIEnd; ++KNI)
3921 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003922 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003923
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003924 // Weed out any names that could not be found by name lookup or, if a
3925 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003926 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003927 LookupResult TmpRes(*this, TypoName, LookupKind);
3928 TmpRes.suppressDiagnostics();
3929 while (!Consumer.empty()) {
3930 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3931 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003932 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3933 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003934 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003935 // If we only want nested name specifier corrections, ignore potential
3936 // corrections that have a different base identifier from the typo.
3937 if (AllowOnlyNNSChanges &&
3938 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3939 TypoCorrectionConsumer::result_iterator Prev = I;
3940 ++I;
3941 DI->second.erase(Prev);
3942 continue;
3943 }
3944
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003945 // If the item already has been looked up or is a keyword, keep it.
3946 // If a validator callback object was given, drop the correction
3947 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003948 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00003949 for (TypoResultList::iterator RI = I->second.begin();
3950 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003951 TypoResultList::iterator Prev = RI;
3952 ++RI;
3953 if (Prev->isResolved()) {
3954 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00003955 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003956 else
3957 Viable = true;
3958 }
3959 }
3960 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003961 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003962 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003963 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003964 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003965 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003966 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003967 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003968
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003969 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003970 TypoCorrection &Candidate = I->second.front();
3971 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003972 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003973 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003974
3975 switch (TmpRes.getResultKind()) {
3976 case LookupResult::NotFound:
3977 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003978 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003979 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003980 // We didn't find this name in our scope, or didn't like what we found;
3981 // ignore it.
3982 {
3983 TypoCorrectionConsumer::result_iterator Next = I;
3984 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003985 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003986 I = Next;
3987 }
3988 break;
3989
3990 case LookupResult::Ambiguous:
3991 // We don't deal with ambiguities.
3992 return TypoCorrection();
3993
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003994 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003995 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003996 // Store all of the Decls for overloaded symbols
3997 for (LookupResult::iterator TRD = TmpRes.begin(),
3998 TRDEnd = TmpRes.end();
3999 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004000 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004001 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004002 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004003 DI->second.erase(Prev);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004004 break;
4005 }
4006
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004007 case LookupResult::Found: {
4008 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004009 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004010 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004011 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004012 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004013 break;
4014 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004015
4016 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004017 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004018
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004019 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004020 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00004021 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004022 // If there are results in the closest possible bucket, stop
4023 break;
4024
4025 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004026 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004027 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004028 for (SmallVector<TypoCorrection,
4029 16>::iterator QRI = QualifiedResults.begin(),
4030 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004031 QRI != QRIEnd; ++QRI) {
4032 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4033 NIEnd = Namespaces.end();
4034 NI != NIEnd; ++NI) {
4035 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004036
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004037 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004038 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004039 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004040
4041 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004042 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004043 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4044
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004045 // Any corrections added below will be validated in subsequent
4046 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004047 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004048 case LookupResult::Found: {
4049 TypoCorrection TC(*QRI);
4050 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
4051 TC.setCorrectionSpecifier(NI->NameSpecifier);
4052 TC.setQualifierDistance(NI->EditDistance);
4053 Consumer.addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004054 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004055 }
4056 case LookupResult::FoundOverloaded: {
4057 TypoCorrection TC(*QRI);
4058 TC.setCorrectionSpecifier(NI->NameSpecifier);
4059 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004060 for (LookupResult::iterator TRD = TmpRes.begin(),
4061 TRDEnd = TmpRes.end();
4062 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004063 TC.addCorrectionDecl(*TRD);
4064 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004065 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004066 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004067 case LookupResult::NotFound:
4068 case LookupResult::NotFoundInCurrentInstantiation:
4069 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004070 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004071 break;
4072 }
4073 }
4074 }
4075 }
4076
4077 QualifiedResults.clear();
4078 }
4079
4080 // No corrections remain...
4081 if (Consumer.empty()) return TypoCorrection();
4082
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004083 TypoResultsMap &BestResults = Consumer.getBestResults();
4084 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004085
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004086 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004087 // If this was an unqualified lookup and we believe the callback
4088 // object wouldn't have filtered out possible corrections, note
4089 // that no correction was found.
4090 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004091 (void)UnqualifiedTyposCorrected[Typo];
4092
4093 return TypoCorrection();
4094 }
4095
Douglas Gregore24b5752010-10-14 20:34:08 +00004096 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004097 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004098 const TypoResultList &CorrectionList = BestResults.begin()->second;
4099 const TypoCorrection &Result = CorrectionList.front();
4100 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004101
Douglas Gregor53e4b552010-10-26 17:18:00 +00004102 // Don't correct to a keyword that's the same as the typo; the keyword
4103 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004104 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4105
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004106 // Record the correction for unqualified lookup.
4107 if (IsUnqualifiedLookup)
4108 UnqualifiedTyposCorrected[Typo] = Result;
4109
David Blaikie6952c012012-10-12 20:00:44 +00004110 TypoCorrection TC = Result;
4111 TC.setCorrectionRange(SS, TypoName);
4112 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004113 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004114 else if (BestResults.size() > 1
4115 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4116 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4117 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4118 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004119 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004120 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004121 // Prefer 'super' when we're completing in a message-receiver
4122 // context.
4123
4124 // Don't correct to a keyword that's the same as the typo; the keyword
4125 // wasn't actually in scope.
4126 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004127
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004128 // Record the correction for unqualified lookup.
4129 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004130 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004131
David Blaikie6952c012012-10-12 20:00:44 +00004132 TypoCorrection TC = BestResults["super"].front();
4133 TC.setCorrectionRange(SS, TypoName);
4134 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004135 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004136
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004137 // If this was an unqualified lookup and we believe the callback object did
4138 // not filter out possible corrections, note that no correction was found.
4139 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004140 (void)UnqualifiedTyposCorrected[Typo];
4141
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004142 return TypoCorrection();
4143}
4144
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004145void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4146 if (!CDecl) return;
4147
4148 if (isKeyword())
4149 CorrectionDecls.clear();
4150
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004151 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004152
4153 if (!CorrectionName)
4154 CorrectionName = CDecl->getDeclName();
4155}
4156
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004157std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4158 if (CorrectionNameSpec) {
4159 std::string tmpBuffer;
4160 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4161 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004162 CorrectionName.printName(PrefixOStream);
4163 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004164 }
4165
4166 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004167}
Kaelyn Uhrain20a7cf42013-04-03 16:59:49 +00004168
4169bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4170 if (!candidate.isResolved())
4171 return true;
4172
4173 if (candidate.isKeyword())
4174 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4175 WantRemainingKeywords || WantObjCSuper;
4176
4177 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4178 CDeclEnd = candidate.end();
4179 CDecl != CDeclEnd; ++CDecl) {
4180 if (!isa<TypeDecl>(*CDecl))
4181 return true;
4182 }
4183
4184 return WantTypeSpecifiers;
4185}