blob: 6ae040ffd7d017b969c78601c02305907951dccc [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) {
Nico Webercac18ad2013-06-20 21:44:55 +0000514 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
515 II == S.getFloat128Identifier()) {
516 // libstdc++4.7's type_traits expects type __float128 to exist, so
517 // insert a dummy type to make that header build in gnu++11 mode.
518 R.addDecl(S.getASTContext().getFloat128StubType());
519 return true;
520 }
521
Douglas Gregor85910982010-02-12 05:48:04 +0000522 // If this is a builtin on this (or all) targets, create the decl.
523 if (unsigned BuiltinID = II->getBuiltinID()) {
524 // In C++, we don't have any predefined library functions like
525 // 'malloc'. Instead, we'll just error.
David Blaikie4e4d0842012-03-11 07:00:24 +0000526 if (S.getLangOpts().CPlusPlus &&
Douglas Gregor85910982010-02-12 05:48:04 +0000527 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
528 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000529
530 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
531 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000532 R.isForRedeclaration(),
533 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000534 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000535 return true;
536 }
537
538 if (R.isForRedeclaration()) {
539 // If we're redeclaring this function anyway, forget that
540 // this was a builtin at all.
541 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
542 }
543
544 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000545 }
546 }
547 }
548
549 return false;
550}
551
Douglas Gregor4923aa22010-07-02 20:37:36 +0000552/// \brief Determine whether we can declare a special member function within
553/// the class at this point.
Richard Smithd0adeb62012-11-27 21:20:31 +0000554static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +0000555 // We need to have a definition for the class.
556 if (!Class->getDefinition() || Class->isDependentContext())
557 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000558
Douglas Gregor4923aa22010-07-02 20:37:36 +0000559 // We can't be in the middle of defining the class.
Richard Smithd0adeb62012-11-27 21:20:31 +0000560 return !Class->isBeingDefined();
Douglas Gregor4923aa22010-07-02 20:37:36 +0000561}
562
563void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000564 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregor22584312010-07-02 23:41:54 +0000565 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000566
567 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000568 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000569 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570
Douglas Gregor22584312010-07-02 23:41:54 +0000571 // If the copy constructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000572 if (Class->needsImplicitCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +0000573 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574
Douglas Gregora376d102010-07-02 21:50:04 +0000575 // If the copy assignment operator has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000576 if (Class->needsImplicitCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000577 DeclareImplicitCopyAssignment(Class);
578
Richard Smith80ad52f2013-01-02 11:42:31 +0000579 if (getLangOpts().CPlusPlus11) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000580 // If the move constructor has not yet been declared, do so now.
581 if (Class->needsImplicitMoveConstructor())
582 DeclareImplicitMoveConstructor(Class); // might not actually do it
583
584 // If the move assignment operator has not yet been declared, do so now.
585 if (Class->needsImplicitMoveAssignment())
586 DeclareImplicitMoveAssignment(Class); // might not actually do it
587 }
588
Douglas Gregor4923aa22010-07-02 20:37:36 +0000589 // If the destructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000590 if (Class->needsImplicitDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000591 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000592}
593
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000594/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000595/// special member function.
596static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
597 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000598 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000599 case DeclarationName::CXXDestructorName:
600 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601
Douglas Gregora376d102010-07-02 21:50:04 +0000602 case DeclarationName::CXXOperatorName:
603 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604
Douglas Gregora376d102010-07-02 21:50:04 +0000605 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000606 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000607 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000608
Douglas Gregora376d102010-07-02 21:50:04 +0000609 return false;
610}
611
612/// \brief If there are any implicit member functions with the given name
613/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000614static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000615 DeclarationName Name,
616 const DeclContext *DC) {
617 if (!DC)
618 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000619
Douglas Gregora376d102010-07-02 21:50:04 +0000620 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000621 case DeclarationName::CXXConstructorName:
622 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithd0adeb62012-11-27 21:20:31 +0000623 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000624 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000625 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000626 S.DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +0000627 if (Record->needsImplicitCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000628 S.DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000629 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000630 Record->needsImplicitMoveConstructor())
631 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000632 }
Douglas Gregor22584312010-07-02 23:41:54 +0000633 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000634
Douglas Gregora376d102010-07-02 21:50:04 +0000635 case DeclarationName::CXXDestructorName:
636 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithe5411b72012-12-01 02:35:44 +0000637 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smithd0adeb62012-11-27 21:20:31 +0000638 CanDeclareSpecialMemberFunction(Record))
Douglas Gregora376d102010-07-02 21:50:04 +0000639 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000640 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000641
Douglas Gregora376d102010-07-02 21:50:04 +0000642 case DeclarationName::CXXOperatorName:
643 if (Name.getCXXOverloadedOperator() != OO_Equal)
644 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000645
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000646 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000647 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000648 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smithe5411b72012-12-01 02:35:44 +0000649 if (Record->needsImplicitCopyAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000650 S.DeclareImplicitCopyAssignment(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000651 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000652 Record->needsImplicitMoveAssignment())
653 S.DeclareImplicitMoveAssignment(Class);
654 }
655 }
Douglas Gregora376d102010-07-02 21:50:04 +0000656 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000657
Douglas Gregora376d102010-07-02 21:50:04 +0000658 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000659 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000660 }
661}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000662
John McCallf36e02d2009-10-09 21:13:30 +0000663// Adds all qualifying matches for a name within a decl context to the
664// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000665static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000666 bool Found = false;
667
Douglas Gregor4923aa22010-07-02 20:37:36 +0000668 // Lazily declare C++ special member functions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000669 if (S.getLangOpts().CPlusPlus)
Douglas Gregora376d102010-07-02 21:50:04 +0000670 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000671
Douglas Gregor4923aa22010-07-02 20:37:36 +0000672 // Perform lookup into this declaration context.
David Blaikie3bc93e32012-12-19 00:45:41 +0000673 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
674 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
675 ++I) {
John McCall46460a62010-01-20 21:53:11 +0000676 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000677 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000678 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000679 Found = true;
680 }
681 }
John McCallf36e02d2009-10-09 21:13:30 +0000682
Douglas Gregor85910982010-02-12 05:48:04 +0000683 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
684 return true;
685
Douglas Gregor48026d22010-01-11 18:40:55 +0000686 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000687 != DeclarationName::CXXConversionFunctionName ||
688 R.getLookupName().getCXXNameType()->isDependentType() ||
689 !isa<CXXRecordDecl>(DC))
690 return Found;
691
692 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000693 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000694 // name lookup. Instead, any conversion function templates visible in the
695 // context of the use are considered. [...]
696 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000697 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000698 return Found;
699
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +0000700 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
701 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000702 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
703 if (!ConvTemplate)
704 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000705
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000706 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000707 // add the conversion function template. When we deduce template
708 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000709 // type of the new declaration with the type of the function template.
710 if (R.isForRedeclaration()) {
711 R.addDecl(ConvTemplate);
712 Found = true;
713 continue;
714 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000715
Douglas Gregor48026d22010-01-11 18:40:55 +0000716 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000717 // [...] For each such operator, if argument deduction succeeds
718 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000719 // name lookup.
720 //
721 // When referencing a conversion function for any purpose other than
722 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000723 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000724 // specialization into the result set. We do this to avoid forcing all
725 // callers to perform special deduction for conversion functions.
Craig Topper93e45992012-09-19 02:26:47 +0000726 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000727 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000728
729 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000730 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
731 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000732
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000733 // Compute the type of the function that we would expect the conversion
734 // function to have, if it were to match the name given.
735 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000736 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
737 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000738 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000739 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000740 QualType ExpectedType
741 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko55431692013-05-05 00:41:58 +0000742 None, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000743
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000744 // Perform template argument deduction against the type that we would
745 // expect the function to have.
746 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
747 Specialization, Info)
748 == Sema::TDK_Success) {
749 R.addDecl(Specialization);
750 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000751 }
752 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000753
John McCallf36e02d2009-10-09 21:13:30 +0000754 return Found;
755}
756
John McCalld7be78a2009-11-10 07:01:13 +0000757// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000758static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000759CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000760 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000761
762 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
763
John McCalld7be78a2009-11-10 07:01:13 +0000764 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000765 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000766
John McCalld7be78a2009-11-10 07:01:13 +0000767 // Perform direct name lookup into the namespaces nominated by the
768 // using directives whose common ancestor is this namespace.
769 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
770 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000771
John McCalld7be78a2009-11-10 07:01:13 +0000772 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000773 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000774 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000775
776 R.resolveKind();
777
778 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000779}
780
781static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000782 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000783 return Ctx->isFileContext();
784 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000785}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000786
Douglas Gregor711be1e2010-03-15 14:33:29 +0000787// Find the next outer declaration context from this scope. This
788// routine actually returns the semantic outer context, which may
789// differ from the lexical context (encoded directly in the Scope
790// stack) when we are parsing a member of a class template. In this
791// case, the second element of the pair will be true, to indicate that
792// name lookup should continue searching in this semantic context when
793// it leaves the current template parameter scope.
794static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
795 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
796 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000797 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000798 OuterS = OuterS->getParent()) {
799 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000800 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000801 break;
802 }
803 }
804
805 // C++ [temp.local]p8:
806 // In the definition of a member of a class template that appears
807 // outside of the namespace containing the class template
808 // definition, the name of a template-parameter hides the name of
809 // a member of this namespace.
810 //
811 // Example:
812 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000813 // namespace N {
814 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000815 //
816 // template<class T> class B {
817 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000818 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000819 // }
820 //
821 // template<class C> void N::B<C>::f(C) {
822 // C b; // C is the template parameter, not N::C
823 // }
824 //
825 // In this example, the lexical context we return is the
826 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000827 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000828 !S->getParent()->isTemplateParamScope())
829 return std::make_pair(Lexical, false);
830
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000831 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000832 // For the example, this is the scope for the template parameters of
833 // template<class C>.
834 Scope *OutermostTemplateScope = S->getParent();
835 while (OutermostTemplateScope->getParent() &&
836 OutermostTemplateScope->getParent()->isTemplateParamScope())
837 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000838
Douglas Gregor711be1e2010-03-15 14:33:29 +0000839 // Find the namespace context in which the original scope occurs. In
840 // the example, this is namespace N.
841 DeclContext *Semantic = DC;
842 while (!Semantic->isFileContext())
843 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000844
Douglas Gregor711be1e2010-03-15 14:33:29 +0000845 // Find the declaration context just outside of the template
846 // parameter scope. This is the context in which the template is
847 // being lexically declaration (a namespace context). In the
848 // example, this is the global scope.
849 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
850 Lexical->Encloses(Semantic))
851 return std::make_pair(Semantic, true);
852
853 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000854}
855
John McCalla24dc2e2009-11-17 02:14:36 +0000856bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000857 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000858
859 DeclarationName Name = R.getLookupName();
860
Douglas Gregora376d102010-07-02 21:50:04 +0000861 // If this is the name of an implicitly-declared special member function,
862 // go through the scope stack to implicitly declare
863 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
864 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
865 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
866 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
867 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000868
Douglas Gregora376d102010-07-02 21:50:04 +0000869 // Implicitly declare member functions with the name we're looking for, if in
870 // fact we are in a scope where it matters.
871
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000872 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000873 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000874 I = IdResolver.begin(Name),
875 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000876
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000877 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000878 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000879 // ...During unqualified name lookup (3.4.1), the names appear as if
880 // they were declared in the nearest enclosing namespace which contains
881 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000882 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000883 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000884 //
885 // For example:
886 // namespace A { int i; }
887 // void foo() {
888 // int i;
889 // {
890 // using namespace A;
891 // ++i; // finds local 'i', A::i appears at global scope
892 // }
893 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000894 //
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000895 UnqualUsingDirectiveSet UDirs;
896 bool VisitedUsingDirectives = false;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000897 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000898 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000899 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
900
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000901 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000902 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000903 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000904 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000905 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000906 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000907 }
908 }
John McCallf36e02d2009-10-09 21:13:30 +0000909 if (Found) {
910 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000911 if (S->isClassScope())
912 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
913 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000914 return true;
915 }
916
Douglas Gregor711be1e2010-03-15 14:33:29 +0000917 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
918 S->getParent() && !S->getParent()->isTemplateParamScope()) {
919 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000920 // found nothing, so look into the contexts between the
Douglas Gregor711be1e2010-03-15 14:33:29 +0000921 // lexical and semantic declaration contexts returned by
922 // findOuterContext(). This implements the name lookup behavior
923 // of C++ [temp.local]p8.
924 Ctx = OutsideOfTemplateParamDC;
925 OutsideOfTemplateParamDC = 0;
926 }
927
928 if (Ctx) {
929 DeclContext *OuterCtx;
930 bool SearchAfterTemplateScope;
931 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
932 if (SearchAfterTemplateScope)
933 OutsideOfTemplateParamDC = OuterCtx;
934
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000935 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000936 // We do not directly look into transparent contexts, since
937 // those entities will be found in the nearest enclosing
938 // non-transparent context.
939 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000940 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000941
942 // We do not look directly into function or method contexts,
943 // since all of the local variables and parameters of the
944 // function/method are present within the Scope.
945 if (Ctx->isFunctionOrMethod()) {
946 // If we have an Objective-C instance method, look for ivars
947 // in the corresponding interface.
948 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
949 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
950 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
951 ObjCInterfaceDecl *ClassDeclared;
952 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000953 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000954 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000955 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
956 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000957 R.resolveKind();
958 return true;
959 }
960 }
961 }
962 }
963
964 continue;
965 }
966
Douglas Gregor6bed88e2013-03-27 12:51:49 +0000967 // If this is a file context, we need to perform unqualified name
968 // lookup considering using directives.
969 if (Ctx->isFileContext()) {
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000970 // If we haven't handled using directives yet, do so now.
971 if (!VisitedUsingDirectives) {
972 // Add using directives from this context up to the top level.
Douglas Gregor34366202013-04-09 01:49:26 +0000973 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
974 if (UCtx->isTransparentContext())
975 continue;
976
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000977 UDirs.visit(UCtx, UCtx);
Douglas Gregor34366202013-04-09 01:49:26 +0000978 }
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000979
980 // Find the innermost file scope, so we can add using directives
981 // from local scopes.
982 Scope *InnermostFileScope = S;
983 while (InnermostFileScope &&
984 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
985 InnermostFileScope = InnermostFileScope->getParent();
986 UDirs.visitScopeChain(Initial, InnermostFileScope);
987
988 UDirs.done();
989
990 VisitedUsingDirectives = true;
991 }
Douglas Gregor6bed88e2013-03-27 12:51:49 +0000992
993 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
994 R.resolveKind();
995 return true;
996 }
997
998 continue;
999 }
1000
Douglas Gregore942bbe2009-09-10 16:57:35 +00001001 // Perform qualified name lookup into this context.
1002 // FIXME: In some cases, we know that every name that could be found by
1003 // this qualified name lookup will also be on the identifier chain. For
1004 // example, inside a class without any base classes, we never need to
1005 // perform qualified lookup because all of the members are on top of the
1006 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001007 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +00001008 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +00001009 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001010 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001011 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001012
John McCalld7be78a2009-11-10 07:01:13 +00001013 // Stop if we ran out of scopes.
1014 // FIXME: This really, really shouldn't be happening.
1015 if (!S) return false;
1016
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001017 // If we are looking for members, no need to look into global/namespace scope.
1018 if (R.getLookupKind() == LookupMemberName)
1019 return false;
1020
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001021 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001022 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +00001023 //
Mike Stump390b4cc2009-05-16 07:39:55 +00001024 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1025 // don't build it for each lookup!
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001026 if (!VisitedUsingDirectives) {
1027 UDirs.visitScopeChain(Initial, S);
1028 UDirs.done();
1029 }
1030
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001031 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001032 // Unqualified name lookup in C++ requires looking into scopes
1033 // that aren't strictly lexical, and therefore we walk through the
1034 // context as well as walking through the scopes.
1035 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001036 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +00001037 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +00001038 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +00001039 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001040 // We found something. Look for anything else in our scope
1041 // with this same name and in an acceptable identifier
1042 // namespace, so that we can construct an overload set if we
1043 // need to.
John McCallf36e02d2009-10-09 21:13:30 +00001044 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +00001045 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001046 }
1047 }
1048
Douglas Gregor00b4b032010-05-14 04:53:42 +00001049 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +00001050 R.resolveKind();
1051 return true;
1052 }
1053
Douglas Gregor00b4b032010-05-14 04:53:42 +00001054 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1055 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1056 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1057 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001058 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001059 // lexical and semantic declaration contexts returned by
1060 // findOuterContext(). This implements the name lookup behavior
1061 // of C++ [temp.local]p8.
1062 Ctx = OutsideOfTemplateParamDC;
1063 OutsideOfTemplateParamDC = 0;
1064 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001065
Douglas Gregor00b4b032010-05-14 04:53:42 +00001066 if (Ctx) {
1067 DeclContext *OuterCtx;
1068 bool SearchAfterTemplateScope;
1069 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1070 if (SearchAfterTemplateScope)
1071 OutsideOfTemplateParamDC = OuterCtx;
1072
1073 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1074 // We do not directly look into transparent contexts, since
1075 // those entities will be found in the nearest enclosing
1076 // non-transparent context.
1077 if (Ctx->isTransparentContext())
1078 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001079
Douglas Gregor00b4b032010-05-14 04:53:42 +00001080 // If we have a context, and it's not a context stashed in the
1081 // template parameter scope for an out-of-line definition, also
1082 // look into that context.
1083 if (!(Found && S && S->isTemplateParamScope())) {
1084 assert(Ctx->isFileContext() &&
1085 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001086
Douglas Gregor00b4b032010-05-14 04:53:42 +00001087 // Look into context considering using-directives.
1088 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1089 Found = true;
1090 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001091
Douglas Gregor00b4b032010-05-14 04:53:42 +00001092 if (Found) {
1093 R.resolveKind();
1094 return true;
1095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001096
Douglas Gregor00b4b032010-05-14 04:53:42 +00001097 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1098 return false;
1099 }
1100 }
1101
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001102 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001103 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001104 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001105
John McCallf36e02d2009-10-09 21:13:30 +00001106 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001107}
1108
Douglas Gregor55368912011-12-14 16:03:29 +00001109/// \brief Retrieve the visible declaration corresponding to D, if any.
1110///
1111/// This routine determines whether the declaration D is visible in the current
1112/// module, with the current imports. If not, it checks whether any
1113/// redeclaration of D is visible, and if so, returns that declaration.
1114///
1115/// \returns D, or a visible previous declaration of D, whichever is more recent
1116/// and visible. If no declaration of D is visible, returns null.
1117static NamedDecl *getVisibleDecl(NamedDecl *D) {
1118 if (LookupResult::isVisible(D))
1119 return D;
1120
Douglas Gregor0782ef22012-01-06 22:05:37 +00001121 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1122 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001123 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Douglas Gregor0782ef22012-01-06 22:05:37 +00001124 if (LookupResult::isVisible(ND))
1125 return ND;
1126 }
Douglas Gregor55368912011-12-14 16:03:29 +00001127 }
1128
1129 return 0;
1130}
1131
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001132/// @brief Perform unqualified name lookup starting from a given
1133/// scope.
1134///
1135/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1136/// used to find names within the current scope. For example, 'x' in
1137/// @code
1138/// int x;
1139/// int f() {
1140/// return x; // unqualified name look finds 'x' in the global scope
1141/// }
1142/// @endcode
1143///
1144/// Different lookup criteria can find different names. For example, a
1145/// particular scope can have both a struct and a function of the same
1146/// name, and each can be found by certain lookup criteria. For more
1147/// information about lookup criteria, see the documentation for the
1148/// class LookupCriteria.
1149///
1150/// @param S The scope from which unqualified name lookup will
1151/// begin. If the lookup criteria permits, name lookup may also search
1152/// in the parent scopes.
1153///
James Dennett8da16872012-06-22 10:32:46 +00001154/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1155/// look up and the lookup kind), and is updated with the results of lookup
1156/// including zero or more declarations and possibly additional information
1157/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001158///
James Dennett8da16872012-06-22 10:32:46 +00001159/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001160bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1161 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001162 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001163
John McCalla24dc2e2009-11-17 02:14:36 +00001164 LookupNameKind NameKind = R.getLookupKind();
1165
David Blaikie4e4d0842012-03-11 07:00:24 +00001166 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001167 // Unqualified name lookup in C/Objective-C is purely lexical, so
1168 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001169 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001170 // Find the nearest non-transparent declaration scope.
1171 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001172 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001173 static_cast<DeclContext *>(S->getEntity())
1174 ->isTransparentContext()))
1175 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001176 }
1177
John McCall1d7c5282009-12-18 10:40:03 +00001178 unsigned IDNS = R.getIdentifierNamespace();
1179
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001180 // Scan up the scope chain looking for a decl that matches this
1181 // identifier that is in the appropriate namespace. This search
1182 // should not take long, as shadowing of names is uncommon, and
1183 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001184 bool LeftStartingScope = false;
1185
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001186 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001187 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001188 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001189 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001190 if (NameKind == LookupRedeclarationWithLinkage) {
1191 // Determine whether this (or a previous) declaration is
1192 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001193 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001194 LeftStartingScope = true;
1195
1196 // If we found something outside of our starting scope that
1197 // does not have linkage, skip it.
1198 if (LeftStartingScope && !((*I)->hasLinkage()))
1199 continue;
1200 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001201 else if (NameKind == LookupObjCImplicitSelfParam &&
1202 !isa<ImplicitParamDecl>(*I))
1203 continue;
1204
Douglas Gregor10ce9322011-12-02 20:08:44 +00001205 // If this declaration is module-private and it came from an AST
1206 // file, we can't see it.
Douglas Gregor447af242012-01-05 01:11:47 +00001207 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor55368912011-12-14 16:03:29 +00001208 if (!D)
Douglas Gregor10ce9322011-12-02 20:08:44 +00001209 continue;
Douglas Gregor55368912011-12-14 16:03:29 +00001210
1211 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001212
Douglas Gregor7a537402012-01-03 23:26:26 +00001213 // Check whether there are any other declarations with the same name
1214 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001215 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001216 // Find the scope in which this declaration was declared (if it
1217 // actually exists in a Scope).
1218 while (S && !S->isDeclScope(D))
1219 S = S->getParent();
1220
1221 // If the scope containing the declaration is the translation unit,
1222 // then we'll need to perform our checks based on the matching
1223 // DeclContexts rather than matching scopes.
1224 if (S && isNamespaceOrTranslationUnitScope(S))
1225 S = 0;
1226
1227 // Compute the DeclContext, if we need it.
1228 DeclContext *DC = 0;
1229 if (!S)
1230 DC = (*I)->getDeclContext()->getRedeclContext();
1231
Douglas Gregorda795b42012-01-04 16:44:10 +00001232 IdentifierResolver::iterator LastI = I;
1233 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001234 if (S) {
1235 // Match based on scope.
1236 if (!S->isDeclScope(*LastI))
1237 break;
1238 } else {
1239 // Match based on DeclContext.
1240 DeclContext *LastDC
1241 = (*LastI)->getDeclContext()->getRedeclContext();
1242 if (!LastDC->Equals(DC))
1243 break;
1244 }
1245
1246 // If the declaration isn't in the right namespace, skip it.
Douglas Gregorda795b42012-01-04 16:44:10 +00001247 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1248 continue;
Douglas Gregor117c4562012-01-13 23:06:53 +00001249
Douglas Gregor447af242012-01-05 01:11:47 +00001250 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregorda795b42012-01-04 16:44:10 +00001251 if (D)
1252 R.addDecl(D);
1253 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001254
Douglas Gregorda795b42012-01-04 16:44:10 +00001255 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001256 }
John McCallf36e02d2009-10-09 21:13:30 +00001257 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001258 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001259 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001260 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001261 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001262 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001263 }
1264
1265 // If we didn't find a use of this identifier, and if the identifier
1266 // corresponds to a compiler builtin, create the decl object for the builtin
1267 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001268 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1269 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001270
Axel Naumannf8291a12011-02-24 16:47:47 +00001271 // If we didn't find a use of this identifier, the ExternalSource
1272 // may be able to handle the situation.
1273 // Note: some lookup failures are expected!
1274 // See e.g. R.isForRedeclaration().
1275 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001276}
1277
John McCall6e247262009-10-10 05:48:19 +00001278/// @brief Perform qualified name lookup in the namespaces nominated by
1279/// using directives by the given context.
1280///
1281/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001282/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001283/// (where X is the global namespace), let S be the set of all
1284/// declarations of m in X and in the transitive closure of all
1285/// namespaces nominated by using-directives in X and its used
1286/// namespaces, except that using-directives are ignored in any
1287/// namespace, including X, directly containing one or more
1288/// declarations of m. No namespace is searched more than once in
1289/// the lookup of a name. If S is the empty set, the program is
1290/// ill-formed. Otherwise, if S has exactly one member, or if the
1291/// context of the reference is a using-declaration
1292/// (namespace.udecl), S is the required set of declarations of
1293/// m. Otherwise if the use of m is not one that allows a unique
1294/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001295///
John McCall6e247262009-10-10 05:48:19 +00001296/// C++98 [namespace.qual]p5:
1297/// During the lookup of a qualified namespace member name, if the
1298/// lookup finds more than one declaration of the member, and if one
1299/// declaration introduces a class name or enumeration name and the
1300/// other declarations either introduce the same object, the same
1301/// enumerator or a set of functions, the non-type name hides the
1302/// class or enumeration name if and only if the declarations are
1303/// from the same namespace; otherwise (the declarations are from
1304/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001305static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001306 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001307 assert(StartDC->isFileContext() && "start context is not a file context");
1308
1309 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1310 DeclContext::udir_iterator E = StartDC->using_directives_end();
1311
1312 if (I == E) return false;
1313
1314 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001315 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001316 Visited.insert(StartDC);
1317
1318 // We have not yet looked into these namespaces, much less added
1319 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001320 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001321
1322 // We have already looked into the initial namespace; seed the queue
1323 // with its using-children.
1324 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001325 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001326 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001327 Queue.push_back(ND);
1328 }
1329
1330 // The easiest way to implement the restriction in [namespace.qual]p5
1331 // is to check whether any of the individual results found a tag
1332 // and, if so, to declare an ambiguity if the final result is not
1333 // a tag.
1334 bool FoundTag = false;
1335 bool FoundNonTag = false;
1336
John McCall7d384dd2009-11-18 07:57:50 +00001337 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001338
1339 bool Found = false;
1340 while (!Queue.empty()) {
1341 NamespaceDecl *ND = Queue.back();
1342 Queue.pop_back();
1343
1344 // We go through some convolutions here to avoid copying results
1345 // between LookupResults.
1346 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001347 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001348 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001349
1350 if (FoundDirect) {
1351 // First do any local hiding.
1352 DirectR.resolveKind();
1353
1354 // If the local result is a tag, remember that.
1355 if (DirectR.isSingleTagDecl())
1356 FoundTag = true;
1357 else
1358 FoundNonTag = true;
1359
1360 // Append the local results to the total results if necessary.
1361 if (UseLocal) {
1362 R.addAllDecls(LocalR);
1363 LocalR.clear();
1364 }
1365 }
1366
1367 // If we find names in this namespace, ignore its using directives.
1368 if (FoundDirect) {
1369 Found = true;
1370 continue;
1371 }
1372
1373 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1374 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001375 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001376 Queue.push_back(Nom);
1377 }
1378 }
1379
1380 if (Found) {
1381 if (FoundTag && FoundNonTag)
1382 R.setAmbiguousQualifiedTagHiding();
1383 else
1384 R.resolveKind();
1385 }
1386
1387 return Found;
1388}
1389
Douglas Gregor8071e422010-08-15 06:18:01 +00001390/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001391static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001392 CXXBasePath &Path,
1393 void *Name) {
1394 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001395
Douglas Gregor8071e422010-08-15 06:18:01 +00001396 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1397 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001398 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001399}
1400
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001401/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001402/// static members, nested types, and enumerators.
1403template<typename InputIterator>
1404static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1405 Decl *D = (*First)->getUnderlyingDecl();
1406 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1407 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001408
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001409 if (isa<CXXMethodDecl>(D)) {
1410 // Determine whether all of the methods are static.
1411 bool AllMethodsAreStatic = true;
1412 for(; First != Last; ++First) {
1413 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001415 if (!isa<CXXMethodDecl>(D)) {
1416 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1417 break;
1418 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001419
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001420 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1421 AllMethodsAreStatic = false;
1422 break;
1423 }
1424 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001425
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001426 if (AllMethodsAreStatic)
1427 return true;
1428 }
1429
1430 return false;
1431}
1432
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001433/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001434///
1435/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1436/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001437/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001438///
1439/// Different lookup criteria can find different names. For example, a
1440/// particular scope can have both a struct and a function of the same
1441/// name, and each can be found by certain lookup criteria. For more
1442/// information about lookup criteria, see the documentation for the
1443/// class LookupCriteria.
1444///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001445/// \param R captures both the lookup criteria and any lookup results found.
1446///
1447/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001448/// search. If the lookup criteria permits, name lookup may also search
1449/// in the parent contexts or (for C++ classes) base classes.
1450///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001451/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001452/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001453///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001454/// \returns true if lookup succeeded, false if it failed.
1455bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1456 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001457 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001458
John McCalla24dc2e2009-11-17 02:14:36 +00001459 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001460 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001462 // Make sure that the declaration context is complete.
1463 assert((!isa<TagDecl>(LookupCtx) ||
1464 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001465 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001466 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001467 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001469 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001470 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001471 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001472 if (isa<CXXRecordDecl>(LookupCtx))
1473 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001474 return true;
1475 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001476
John McCall6e247262009-10-10 05:48:19 +00001477 // Don't descend into implied contexts for redeclarations.
1478 // C++98 [namespace.qual]p6:
1479 // In a declaration for a namespace member in which the
1480 // declarator-id is a qualified-id, given that the qualified-id
1481 // for the namespace member has the form
1482 // nested-name-specifier unqualified-id
1483 // the unqualified-id shall name a member of the namespace
1484 // designated by the nested-name-specifier.
1485 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001486 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001487 return false;
1488
John McCalla24dc2e2009-11-17 02:14:36 +00001489 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001490 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001491 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001492
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001493 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001494 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001495 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001496 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001497 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001498
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001499 // If we're performing qualified name lookup into a dependent class,
1500 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001501 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001502 // template instantiation time (at which point all bases will be available)
1503 // or we have to fail.
1504 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1505 LookupRec->hasAnyDependentBases()) {
1506 R.setNotFoundInCurrentInstantiation();
1507 return false;
1508 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001509
Douglas Gregor7176fff2009-01-15 00:26:24 +00001510 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001511 CXXBasePaths Paths;
1512 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001513
1514 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001515 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001516 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001517 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001518 case LookupOrdinaryName:
1519 case LookupMemberName:
1520 case LookupRedeclarationWithLinkage:
1521 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1522 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001523
Douglas Gregora8f32e02009-10-06 17:59:45 +00001524 case LookupTagName:
1525 BaseCallback = &CXXRecordDecl::FindTagMember;
1526 break;
John McCall9f54ad42009-12-10 09:41:52 +00001527
Douglas Gregor8071e422010-08-15 06:18:01 +00001528 case LookupAnyName:
1529 BaseCallback = &LookupAnyMember;
1530 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001531
John McCall9f54ad42009-12-10 09:41:52 +00001532 case LookupUsingDeclName:
1533 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001534
Douglas Gregora8f32e02009-10-06 17:59:45 +00001535 case LookupOperatorName:
1536 case LookupNamespaceName:
1537 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001538 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001539 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001540 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001541
Douglas Gregora8f32e02009-10-06 17:59:45 +00001542 case LookupNestedNameSpecifierName:
1543 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1544 break;
1545 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546
John McCalla24dc2e2009-11-17 02:14:36 +00001547 if (!LookupRec->lookupInBases(BaseCallback,
1548 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001549 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001550
John McCall92f88312010-01-23 00:46:32 +00001551 R.setNamingClass(LookupRec);
1552
Douglas Gregor7176fff2009-01-15 00:26:24 +00001553 // C++ [class.member.lookup]p2:
1554 // [...] If the resulting set of declarations are not all from
1555 // sub-objects of the same type, or the set has a nonstatic member
1556 // and includes members from distinct sub-objects, there is an
1557 // ambiguity and the program is ill-formed. Otherwise that set is
1558 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001559 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001560 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001561 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001562
Douglas Gregora8f32e02009-10-06 17:59:45 +00001563 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001564 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001565 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001566
John McCall46460a62010-01-20 21:53:11 +00001567 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1568 // across all paths.
1569 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001570
Douglas Gregor7176fff2009-01-15 00:26:24 +00001571 // Determine whether we're looking at a distinct sub-object or not.
1572 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001573 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001574 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1575 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001576 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001577 }
1578
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001579 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001580 != Context.getCanonicalType(PathElement.Base->getType())) {
1581 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001582 // different types. If the declaration sets aren't the same, this
1583 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001584 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001585 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001586 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1587 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001588
David Blaikie3bc93e32012-12-19 00:45:41 +00001589 while (FirstD != FirstPath->Decls.end() &&
1590 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001591 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1592 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1593 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001594
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001595 ++FirstD;
1596 ++CurrentD;
1597 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001598
David Blaikie3bc93e32012-12-19 00:45:41 +00001599 if (FirstD == FirstPath->Decls.end() &&
1600 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001601 continue;
1602 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001603
John McCallf36e02d2009-10-09 21:13:30 +00001604 R.setAmbiguousBaseSubobjectTypes(Paths);
1605 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001606 }
1607
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001608 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001609 // We have a different subobject of the same type.
1610
1611 // C++ [class.member.lookup]p5:
1612 // A static member, a nested type or an enumerator defined in
1613 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001614 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001615 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001616 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001617
Douglas Gregor7176fff2009-01-15 00:26:24 +00001618 // We have found a nonstatic member name in multiple, distinct
1619 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001620 R.setAmbiguousBaseSubobjects(Paths);
1621 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001622 }
1623 }
1624
1625 // Lookup in a base class succeeded; return these results.
1626
David Blaikie3bc93e32012-12-19 00:45:41 +00001627 DeclContext::lookup_result DR = Paths.front().Decls;
1628 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001629 NamedDecl *D = *I;
1630 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1631 D->getAccess());
1632 R.addDecl(D, AS);
1633 }
John McCallf36e02d2009-10-09 21:13:30 +00001634 R.resolveKind();
1635 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001636}
1637
1638/// @brief Performs name lookup for a name that was parsed in the
1639/// source code, and may contain a C++ scope specifier.
1640///
1641/// This routine is a convenience routine meant to be called from
1642/// contexts that receive a name and an optional C++ scope specifier
1643/// (e.g., "N::M::x"). It will then perform either qualified or
1644/// unqualified name lookup (with LookupQualifiedName or LookupName,
1645/// respectively) on the given name and return those results.
1646///
1647/// @param S The scope from which unqualified name lookup will
1648/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001649///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001650/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001651///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001652/// @param EnteringContext Indicates whether we are going to enter the
1653/// context of the scope-specifier SS (if present).
1654///
John McCallf36e02d2009-10-09 21:13:30 +00001655/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001656bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001657 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001658 if (SS && SS->isInvalid()) {
1659 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001660 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001661 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001662 }
Mike Stump1eb44332009-09-09 15:08:12 +00001663
Douglas Gregor495c35d2009-08-25 22:51:20 +00001664 if (SS && SS->isSet()) {
1665 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001666 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001667 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001668 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001669 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001670
John McCalla24dc2e2009-11-17 02:14:36 +00001671 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001672 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001673 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001674
Douglas Gregor495c35d2009-08-25 22:51:20 +00001675 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001676 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001677 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001678 R.setNotFoundInCurrentInstantiation();
1679 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001680 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001681 }
1682
Mike Stump1eb44332009-09-09 15:08:12 +00001683 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001684 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001685}
1686
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001687
James Dennett16ae9de2012-06-22 10:16:05 +00001688/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001689/// from name lookup.
1690///
James Dennett16ae9de2012-06-22 10:16:05 +00001691/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump1eb44332009-09-09 15:08:12 +00001692///
James Dennett16ae9de2012-06-22 10:16:05 +00001693/// \returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001694bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001695 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1696
John McCalla24dc2e2009-11-17 02:14:36 +00001697 DeclarationName Name = Result.getLookupName();
1698 SourceLocation NameLoc = Result.getNameLoc();
1699 SourceRange LookupRange = Result.getContextRange();
1700
John McCall6e247262009-10-10 05:48:19 +00001701 switch (Result.getAmbiguityKind()) {
1702 case LookupResult::AmbiguousBaseSubobjects: {
1703 CXXBasePaths *Paths = Result.getBasePaths();
1704 QualType SubobjectType = Paths->front().back().Base->getType();
1705 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1706 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1707 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001708
David Blaikie3bc93e32012-12-19 00:45:41 +00001709 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001710 while (isa<CXXMethodDecl>(*Found) &&
1711 cast<CXXMethodDecl>(*Found)->isStatic())
1712 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001713
John McCall6e247262009-10-10 05:48:19 +00001714 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001715
John McCall6e247262009-10-10 05:48:19 +00001716 return true;
1717 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001718
John McCall6e247262009-10-10 05:48:19 +00001719 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001720 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1721 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001722
John McCall6e247262009-10-10 05:48:19 +00001723 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001724 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001725 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1726 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001727 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001728 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001729 if (DeclsPrinted.insert(D).second)
1730 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1731 }
1732
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001733 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001734 }
1735
John McCall6e247262009-10-10 05:48:19 +00001736 case LookupResult::AmbiguousTagHiding: {
1737 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001738
John McCall6e247262009-10-10 05:48:19 +00001739 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1740
1741 LookupResult::iterator DI, DE = Result.end();
1742 for (DI = Result.begin(); DI != DE; ++DI)
1743 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1744 TagDecls.insert(TD);
1745 Diag(TD->getLocation(), diag::note_hidden_tag);
1746 }
1747
1748 for (DI = Result.begin(); DI != DE; ++DI)
1749 if (!isa<TagDecl>(*DI))
1750 Diag((*DI)->getLocation(), diag::note_hiding_object);
1751
1752 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001753 LookupResult::Filter F = Result.makeFilter();
1754 while (F.hasNext()) {
1755 if (TagDecls.count(F.next()))
1756 F.erase();
1757 }
1758 F.done();
John McCall6e247262009-10-10 05:48:19 +00001759
1760 return true;
1761 }
1762
1763 case LookupResult::AmbiguousReference: {
1764 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001765
John McCall6e247262009-10-10 05:48:19 +00001766 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1767 for (; DI != DE; ++DI)
1768 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001769
John McCall6e247262009-10-10 05:48:19 +00001770 return true;
1771 }
1772 }
1773
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001774 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001775}
Douglas Gregorfa047642009-02-04 00:32:51 +00001776
John McCallc7e04da2010-05-28 18:45:08 +00001777namespace {
1778 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001779 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001780 Sema::AssociatedNamespaceSet &Namespaces,
1781 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001782 : S(S), Namespaces(Namespaces), Classes(Classes),
1783 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001784 }
1785
1786 Sema &S;
1787 Sema::AssociatedNamespaceSet &Namespaces;
1788 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001789 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001790 };
1791}
1792
Mike Stump1eb44332009-09-09 15:08:12 +00001793static void
John McCallc7e04da2010-05-28 18:45:08 +00001794addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001795
Douglas Gregor54022952010-04-30 07:08:38 +00001796static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1797 DeclContext *Ctx) {
1798 // Add the associated namespace for this class.
1799
1800 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1801 // be a locally scoped record.
1802
Sebastian Redl410c4f22010-08-31 20:53:31 +00001803 // We skip out of inline namespaces. The innermost non-inline namespace
1804 // contains all names of all its nested inline namespaces anyway, so we can
1805 // replace the entire inline namespace tree with its root.
1806 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1807 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001808 Ctx = Ctx->getParent();
1809
John McCall6ff07852009-08-07 22:18:02 +00001810 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001811 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001812}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001813
Mike Stump1eb44332009-09-09 15:08:12 +00001814// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001815// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001816static void
John McCallc7e04da2010-05-28 18:45:08 +00001817addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1818 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001819 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001820 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001821 switch (Arg.getKind()) {
1822 case TemplateArgument::Null:
1823 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Douglas Gregor69be8d62009-07-08 07:51:57 +00001825 case TemplateArgument::Type:
1826 // [...] the namespaces and classes associated with the types of the
1827 // template arguments provided for template type parameters (excluding
1828 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001829 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001830 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001832 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001833 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001834 // [...] the namespaces in which any template template arguments are
1835 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001836 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001837 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001838 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001839 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001840 DeclContext *Ctx = ClassTemplate->getDeclContext();
1841 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001842 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001843 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001844 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001845 }
1846 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001847 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001848
Douglas Gregor788cd062009-11-11 01:00:40 +00001849 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001850 case TemplateArgument::Integral:
1851 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001852 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001853 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001854 // associated namespaces. ]
1855 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregor69be8d62009-07-08 07:51:57 +00001857 case TemplateArgument::Pack:
1858 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1859 PEnd = Arg.pack_end();
1860 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001861 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001862 break;
1863 }
1864}
1865
Douglas Gregorfa047642009-02-04 00:32:51 +00001866// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001867// argument-dependent lookup with an argument of class type
1868// (C++ [basic.lookup.koenig]p2).
1869static void
John McCallc7e04da2010-05-28 18:45:08 +00001870addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1871 CXXRecordDecl *Class) {
1872
1873 // Just silently ignore anything whose name is __va_list_tag.
1874 if (Class->getDeclName() == Result.S.VAListTagName)
1875 return;
1876
Douglas Gregorfa047642009-02-04 00:32:51 +00001877 // C++ [basic.lookup.koenig]p2:
1878 // [...]
1879 // -- If T is a class type (including unions), its associated
1880 // classes are: the class itself; the class of which it is a
1881 // member, if any; and its direct and indirect base
1882 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001883 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001884
1885 // Add the class of which it is a member, if any.
1886 DeclContext *Ctx = Class->getDeclContext();
1887 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001888 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001889 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001890 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Douglas Gregorfa047642009-02-04 00:32:51 +00001892 // Add the class itself. If we've already seen this class, we don't
1893 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001894 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001895 return;
1896
Mike Stump1eb44332009-09-09 15:08:12 +00001897 // -- If T is a template-id, its associated namespaces and classes are
1898 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001899 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001900 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001901 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001902 // namespaces in which any template template arguments are defined; and
1903 // the classes in which any member templates used as template template
1904 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001905 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001906 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001907 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1908 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1909 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001910 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001911 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001912 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Douglas Gregor69be8d62009-07-08 07:51:57 +00001914 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1915 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001916 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001917 }
Mike Stump1eb44332009-09-09 15:08:12 +00001918
John McCall86ff3082010-02-04 22:26:26 +00001919 // Only recurse into base classes for complete types.
1920 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00001921 QualType type = Result.S.Context.getTypeDeclType(Class);
1922 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
1923 /*no diagnostic*/ 0))
1924 return;
John McCall86ff3082010-02-04 22:26:26 +00001925 }
1926
Douglas Gregorfa047642009-02-04 00:32:51 +00001927 // Add direct and indirect base classes along with their associated
1928 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001929 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001930 Bases.push_back(Class);
1931 while (!Bases.empty()) {
1932 // Pop this class off the stack.
1933 Class = Bases.back();
1934 Bases.pop_back();
1935
1936 // Visit the base classes.
1937 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1938 BaseEnd = Class->bases_end();
1939 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001940 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001941 // In dependent contexts, we do ADL twice, and the first time around,
1942 // the base type might be a dependent TemplateSpecializationType, or a
1943 // TemplateTypeParmType. If that happens, simply ignore it.
1944 // FIXME: If we want to support export, we probably need to add the
1945 // namespace of the template in a TemplateSpecializationType, or even
1946 // the classes and namespaces of known non-dependent arguments.
1947 if (!BaseType)
1948 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001949 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001950 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001951 // Find the associated namespace for this base class.
1952 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001953 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001954
1955 // Make sure we visit the bases of this base class.
1956 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1957 Bases.push_back(BaseDecl);
1958 }
1959 }
1960 }
1961}
1962
1963// \brief Add the associated classes and namespaces for
1964// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001965// (C++ [basic.lookup.koenig]p2).
1966static void
John McCallc7e04da2010-05-28 18:45:08 +00001967addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001968 // C++ [basic.lookup.koenig]p2:
1969 //
1970 // For each argument type T in the function call, there is a set
1971 // of zero or more associated namespaces and a set of zero or more
1972 // associated classes to be considered. The sets of namespaces and
1973 // classes is determined entirely by the types of the function
1974 // arguments (and the namespace of any template template
1975 // argument). Typedef names and using-declarations used to specify
1976 // the types do not contribute to this set. The sets of namespaces
1977 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001978
Chris Lattner5f9e2722011-07-23 10:55:15 +00001979 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001980 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1981
Douglas Gregorfa047642009-02-04 00:32:51 +00001982 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001983 switch (T->getTypeClass()) {
1984
1985#define TYPE(Class, Base)
1986#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1987#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1988#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1989#define ABSTRACT_TYPE(Class, Base)
1990#include "clang/AST/TypeNodes.def"
1991 // T is canonical. We can also ignore dependent types because
1992 // we don't need to do ADL at the definition point, but if we
1993 // wanted to implement template export (or if we find some other
1994 // use for associated classes and namespaces...) this would be
1995 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001996 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001997
John McCallfa4edcf2010-05-28 06:08:54 +00001998 // -- If T is a pointer to U or an array of U, its associated
1999 // namespaces and classes are those associated with U.
2000 case Type::Pointer:
2001 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2002 continue;
2003 case Type::ConstantArray:
2004 case Type::IncompleteArray:
2005 case Type::VariableArray:
2006 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2007 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002008
John McCallfa4edcf2010-05-28 06:08:54 +00002009 // -- If T is a fundamental type, its associated sets of
2010 // namespaces and classes are both empty.
2011 case Type::Builtin:
2012 break;
2013
2014 // -- If T is a class type (including unions), its associated
2015 // classes are: the class itself; the class of which it is a
2016 // member, if any; and its direct and indirect base
2017 // classes. Its associated namespaces are the namespaces in
2018 // which its associated classes are defined.
2019 case Type::Record: {
2020 CXXRecordDecl *Class
2021 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002022 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00002023 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002024 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00002025
John McCallfa4edcf2010-05-28 06:08:54 +00002026 // -- If T is an enumeration type, its associated namespace is
2027 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002028 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00002029 // it has no associated class.
2030 case Type::Enum: {
2031 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002032
John McCallfa4edcf2010-05-28 06:08:54 +00002033 DeclContext *Ctx = Enum->getDeclContext();
2034 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002035 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002036
John McCallfa4edcf2010-05-28 06:08:54 +00002037 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002038 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002039
John McCallfa4edcf2010-05-28 06:08:54 +00002040 break;
2041 }
2042
2043 // -- If T is a function type, its associated namespaces and
2044 // classes are those associated with the function parameter
2045 // types and those associated with the return type.
2046 case Type::FunctionProto: {
2047 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2048 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2049 ArgEnd = Proto->arg_type_end();
2050 Arg != ArgEnd; ++Arg)
2051 Queue.push_back(Arg->getTypePtr());
2052 // fallthrough
2053 }
2054 case Type::FunctionNoProto: {
2055 const FunctionType *FnType = cast<FunctionType>(T);
2056 T = FnType->getResultType().getTypePtr();
2057 continue;
2058 }
2059
2060 // -- If T is a pointer to a member function of a class X, its
2061 // associated namespaces and classes are those associated
2062 // with the function parameter types and return type,
2063 // together with those associated with X.
2064 //
2065 // -- If T is a pointer to a data member of class X, its
2066 // associated namespaces and classes are those associated
2067 // with the member type together with those associated with
2068 // X.
2069 case Type::MemberPointer: {
2070 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2071
2072 // Queue up the class type into which this points.
2073 Queue.push_back(MemberPtr->getClass());
2074
2075 // And directly continue with the pointee type.
2076 T = MemberPtr->getPointeeType().getTypePtr();
2077 continue;
2078 }
2079
2080 // As an extension, treat this like a normal pointer.
2081 case Type::BlockPointer:
2082 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2083 continue;
2084
2085 // References aren't covered by the standard, but that's such an
2086 // obvious defect that we cover them anyway.
2087 case Type::LValueReference:
2088 case Type::RValueReference:
2089 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2090 continue;
2091
2092 // These are fundamental types.
2093 case Type::Vector:
2094 case Type::ExtVector:
2095 case Type::Complex:
2096 break;
2097
Richard Smithdc7a4f52013-04-30 13:56:41 +00002098 // Non-deduced auto types only get here for error cases.
2099 case Type::Auto:
2100 break;
2101
Douglas Gregorf25760e2011-04-12 01:02:45 +00002102 // If T is an Objective-C object or interface type, or a pointer to an
2103 // object or interface type, the associated namespace is the global
2104 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002105 case Type::ObjCObject:
2106 case Type::ObjCInterface:
2107 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002108 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002109 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002110
2111 // Atomic types are just wrappers; use the associations of the
2112 // contained type.
2113 case Type::Atomic:
2114 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2115 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002116 }
2117
2118 if (Queue.empty()) break;
2119 T = Queue.back();
2120 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002121 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002122}
2123
2124/// \brief Find the associated classes and namespaces for
2125/// argument-dependent lookup for a call with the given set of
2126/// arguments.
2127///
2128/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002129/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002130/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002131void
John McCall42f48fb2012-08-24 20:38:34 +00002132Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2133 llvm::ArrayRef<Expr *> Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002134 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002135 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002136 AssociatedNamespaces.clear();
2137 AssociatedClasses.clear();
2138
John McCall42f48fb2012-08-24 20:38:34 +00002139 AssociatedLookup Result(*this, InstantiationLoc,
2140 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002141
Douglas Gregorfa047642009-02-04 00:32:51 +00002142 // C++ [basic.lookup.koenig]p2:
2143 // For each argument type T in the function call, there is a set
2144 // of zero or more associated namespaces and a set of zero or more
2145 // associated classes to be considered. The sets of namespaces and
2146 // classes is determined entirely by the types of the function
2147 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002148 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002149 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002150 Expr *Arg = Args[ArgIdx];
2151
2152 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002153 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002154 continue;
2155 }
2156
2157 // [...] In addition, if the argument is the name or address of a
2158 // set of overloaded functions and/or function templates, its
2159 // associated classes and namespaces are the union of those
2160 // associated with each of the members of the set: the namespace
2161 // in which the function or function template is defined and the
2162 // classes and namespaces associated with its (non-dependent)
2163 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002164 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002165 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002166 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002167 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002168
John McCallc7e04da2010-05-28 18:45:08 +00002169 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2170 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002171
John McCallc7e04da2010-05-28 18:45:08 +00002172 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2173 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002174 // Look through any using declarations to find the underlying function.
2175 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002176
Chandler Carruthbd647292009-12-29 06:17:27 +00002177 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2178 if (!FDecl)
2179 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002180
2181 // Add the classes and namespaces associated with the parameter
2182 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002183 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002184 }
2185 }
2186}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002187
2188/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2189/// an acceptable non-member overloaded operator for a call whose
2190/// arguments have types T1 (and, if non-empty, T2). This routine
2191/// implements the check in C++ [over.match.oper]p3b2 concerning
2192/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002193static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002194IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2195 QualType T1, QualType T2,
2196 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002197 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2198 return true;
2199
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002200 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2201 return true;
2202
John McCall183700f2009-09-21 23:43:11 +00002203 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002204 if (Proto->getNumArgs() < 1)
2205 return false;
2206
2207 if (T1->isEnumeralType()) {
2208 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002209 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002210 return true;
2211 }
2212
2213 if (Proto->getNumArgs() < 2)
2214 return false;
2215
2216 if (!T2.isNull() && T2->isEnumeralType()) {
2217 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002218 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002219 return true;
2220 }
2221
2222 return false;
2223}
2224
John McCall7d384dd2009-11-18 07:57:50 +00002225NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002226 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002227 LookupNameKind NameKind,
2228 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002229 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002230 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002231 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002232}
2233
Douglas Gregor6e378de2009-04-23 23:18:26 +00002234/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002235ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002236 SourceLocation IdLoc,
2237 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002238 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002239 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002240 return cast_or_null<ObjCProtocolDecl>(D);
2241}
2242
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002243void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002244 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002245 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002246 // C++ [over.match.oper]p3:
2247 // -- The set of non-member candidates is the result of the
2248 // unqualified lookup of operator@ in the context of the
2249 // expression according to the usual rules for name lookup in
2250 // unqualified function calls (3.4.2) except that all member
2251 // functions are ignored. However, if no operand has a class
2252 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002253 // that have a first parameter of type T1 or "reference to
2254 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002255 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002256 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002257 // when T2 is an enumeration type, are candidate functions.
2258 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002259 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2260 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002262 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2263
John McCallf36e02d2009-10-09 21:13:30 +00002264 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002265 return;
2266
2267 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2268 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002269 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002271 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002272 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002273 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002274 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002275 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002276 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002277 // later?
2278 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002279 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002280 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002281 }
2282}
2283
Sean Huntc39b6bc2011-06-24 02:11:39 +00002284Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002285 CXXSpecialMember SM,
2286 bool ConstArg,
2287 bool VolatileArg,
2288 bool RValueThis,
2289 bool ConstThis,
2290 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002291 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002292 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002293 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002294 if (RValueThis || ConstThis || VolatileThis)
2295 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2296 "constructors and destructors always have unqualified lvalue this");
2297 if (ConstArg || VolatileArg)
2298 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2299 "parameter-less special members can't have qualified arguments");
2300
2301 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002302 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002303 ID.AddInteger(SM);
2304 ID.AddInteger(ConstArg);
2305 ID.AddInteger(VolatileArg);
2306 ID.AddInteger(RValueThis);
2307 ID.AddInteger(ConstThis);
2308 ID.AddInteger(VolatileThis);
2309
2310 void *InsertPoint;
2311 SpecialMemberOverloadResult *Result =
2312 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2313
2314 // This was already cached
2315 if (Result)
2316 return Result;
2317
Sean Hunt30543582011-06-07 00:11:58 +00002318 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2319 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002320 SpecialMemberCache.InsertNode(Result, InsertPoint);
2321
2322 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002323 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002324 DeclareImplicitDestructor(RD);
2325 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002326 assert(DD && "record without a destructor");
2327 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002328 Result->setKind(DD->isDeleted() ?
2329 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002330 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002331 return Result;
2332 }
2333
Sean Huntb320e0c2011-06-10 03:50:41 +00002334 // Prepare for overload resolution. Here we construct a synthetic argument
2335 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002336 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002337 DeclarationName Name;
2338 Expr *Arg = 0;
2339 unsigned NumArgs;
2340
Richard Smith704c8f72012-04-20 18:46:14 +00002341 QualType ArgType = CanTy;
2342 ExprValueKind VK = VK_LValue;
2343
Sean Huntb320e0c2011-06-10 03:50:41 +00002344 if (SM == CXXDefaultConstructor) {
2345 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2346 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002347 if (RD->needsImplicitDefaultConstructor())
2348 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002349 } else {
2350 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2351 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002352 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002353 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002354 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002355 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002356 } else {
2357 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002358 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002359 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002360 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002361 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002362 }
2363
Sean Huntb320e0c2011-06-10 03:50:41 +00002364 if (ConstArg)
2365 ArgType.addConst();
2366 if (VolatileArg)
2367 ArgType.addVolatile();
2368
2369 // This isn't /really/ specified by the standard, but it's implied
2370 // we should be working from an RValue in the case of move to ensure
2371 // that we prefer to bind to rvalue references, and an LValue in the
2372 // case of copy to ensure we don't bind to rvalue references.
2373 // Possibly an XValue is actually correct in the case of move, but
2374 // there is no semantic difference for class types in this restricted
2375 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002376 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002377 VK = VK_LValue;
2378 else
2379 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002380 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002381
Richard Smith704c8f72012-04-20 18:46:14 +00002382 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2383
2384 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002385 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002386 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002387 }
2388
2389 // Create the object argument
2390 QualType ThisTy = CanTy;
2391 if (ConstThis)
2392 ThisTy.addConst();
2393 if (VolatileThis)
2394 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002395 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002396 OpaqueValueExpr(SourceLocation(), ThisTy,
2397 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002398
2399 // Now we perform lookup on the name we computed earlier and do overload
2400 // resolution. Lookup is only performed directly into the class since there
2401 // will always be a (possibly implicit) declaration to shadow any others.
2402 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002403 DeclContext::lookup_result R = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002404
David Blaikie3bc93e32012-12-19 00:45:41 +00002405 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002406 "lookup for a constructor or assignment operator was empty");
David Blaikie3bc93e32012-12-19 00:45:41 +00002407 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002408 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002409
Sean Huntc39b6bc2011-06-24 02:11:39 +00002410 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002411 continue;
2412
Sean Huntc39b6bc2011-06-24 02:11:39 +00002413 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2414 // FIXME: [namespace.udecl]p15 says that we should only consider a
2415 // using declaration here if it does not match a declaration in the
2416 // derived class. We do not implement this correctly in other cases
2417 // either.
2418 Cand = U->getTargetDecl();
2419
2420 if (Cand->isInvalidDecl())
2421 continue;
2422 }
2423
2424 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002425 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002426 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002427 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2428 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002429 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002430 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2431 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002432 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002433 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002434 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2435 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002436 RD, 0, ThisTy, Classification,
2437 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002438 OCS, true);
2439 else
2440 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002441 0, llvm::makeArrayRef(&Arg, NumArgs),
2442 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002443 } else {
2444 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002445 }
2446 }
2447
2448 OverloadCandidateSet::iterator Best;
2449 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2450 case OR_Success:
2451 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002452 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002453 break;
2454
2455 case OR_Deleted:
2456 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002457 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002458 break;
2459
2460 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002461 Result->setMethod(0);
2462 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2463 break;
2464
Sean Huntb320e0c2011-06-10 03:50:41 +00002465 case OR_No_Viable_Function:
2466 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002467 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002468 break;
2469 }
2470
2471 return Result;
2472}
2473
2474/// \brief Look up the default constructor for the given class.
2475CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002476 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002477 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2478 false, false);
2479
2480 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002481}
2482
Sean Hunt661c67a2011-06-21 23:42:56 +00002483/// \brief Look up the copying constructor for the given class.
2484CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002485 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002486 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2487 "non-const, non-volatile qualifiers for copy ctor arg");
2488 SpecialMemberOverloadResult *Result =
2489 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2490 Quals & Qualifiers::Volatile, false, false, false);
2491
Sean Huntc530d172011-06-10 04:44:37 +00002492 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2493}
2494
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002495/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002496CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2497 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002498 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002499 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2500 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002501
2502 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2503}
2504
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002505/// \brief Look up the constructors for the given class.
2506DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002507 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002508 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002509 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002510 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002511 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002512 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002513 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002514 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002515 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002516
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002517 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2518 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2519 return Class->lookup(Name);
2520}
2521
Sean Hunt661c67a2011-06-21 23:42:56 +00002522/// \brief Look up the copying assignment operator for the given class.
2523CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2524 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002525 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002526 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2527 "non-const, non-volatile qualifiers for copy assignment arg");
2528 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2529 "non-const, non-volatile qualifiers for copy assignment this");
2530 SpecialMemberOverloadResult *Result =
2531 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2532 Quals & Qualifiers::Volatile, RValueThis,
2533 ThisQuals & Qualifiers::Const,
2534 ThisQuals & Qualifiers::Volatile);
2535
Sean Hunt661c67a2011-06-21 23:42:56 +00002536 return Result->getMethod();
2537}
2538
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002539/// \brief Look up the moving assignment operator for the given class.
2540CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002541 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002542 bool RValueThis,
2543 unsigned ThisQuals) {
2544 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2545 "non-const, non-volatile qualifiers for copy assignment this");
2546 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002547 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2548 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002549 ThisQuals & Qualifiers::Const,
2550 ThisQuals & Qualifiers::Volatile);
2551
2552 return Result->getMethod();
2553}
2554
Douglas Gregordb89f282010-07-01 22:47:18 +00002555/// \brief Look for the destructor of the given class.
2556///
Sean Huntc5c9b532011-06-03 21:10:40 +00002557/// During semantic analysis, this routine should be used in lieu of
2558/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002559///
2560/// \returns The destructor for this class.
2561CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002562 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2563 false, false, false,
2564 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002565}
2566
Richard Smith36f5cfe2012-03-09 08:00:36 +00002567/// LookupLiteralOperator - Determine which literal operator should be used for
2568/// a user-defined literal, per C++11 [lex.ext].
2569///
2570/// Normal overload resolution is not used to select which literal operator to
2571/// call for a user-defined literal. Look up the provided literal operator name,
2572/// and filter the results to the appropriate set for the given argument types.
2573Sema::LiteralOperatorLookupResult
2574Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2575 ArrayRef<QualType> ArgTys,
2576 bool AllowRawAndTemplate) {
2577 LookupName(R, S);
2578 assert(R.getResultKind() != LookupResult::Ambiguous &&
2579 "literal operator lookup can't be ambiguous");
2580
2581 // Filter the lookup results appropriately.
2582 LookupResult::Filter F = R.makeFilter();
2583
2584 bool FoundTemplate = false;
2585 bool FoundRaw = false;
2586 bool FoundExactMatch = false;
2587
2588 while (F.hasNext()) {
2589 Decl *D = F.next();
2590 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2591 D = USD->getTargetDecl();
2592
2593 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2594 bool IsRaw = false;
2595 bool IsExactMatch = false;
2596
Douglas Gregor7e0c2272013-04-10 05:18:00 +00002597 // If the declaration we found is invalid, skip it.
2598 if (D->isInvalidDecl()) {
2599 F.erase();
2600 continue;
2601 }
2602
Richard Smith36f5cfe2012-03-09 08:00:36 +00002603 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2604 if (FD->getNumParams() == 1 &&
2605 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2606 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002607 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002608 IsExactMatch = true;
2609 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2610 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2611 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2612 IsExactMatch = false;
2613 break;
2614 }
2615 }
2616 }
2617 }
2618
2619 if (IsExactMatch) {
2620 FoundExactMatch = true;
2621 AllowRawAndTemplate = false;
2622 if (FoundRaw || FoundTemplate) {
2623 // Go through again and remove the raw and template decls we've
2624 // already found.
2625 F.restart();
2626 FoundRaw = FoundTemplate = false;
2627 }
2628 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2629 FoundTemplate |= IsTemplate;
2630 FoundRaw |= IsRaw;
2631 } else {
2632 F.erase();
2633 }
2634 }
2635
2636 F.done();
2637
2638 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2639 // parameter type, that is used in preference to a raw literal operator
2640 // or literal operator template.
2641 if (FoundExactMatch)
2642 return LOLR_Cooked;
2643
2644 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2645 // operator template, but not both.
2646 if (FoundRaw && FoundTemplate) {
2647 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2648 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2649 Decl *D = *I;
2650 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2651 D = USD->getTargetDecl();
2652 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2653 D = FunTmpl->getTemplatedDecl();
2654 NoteOverloadCandidate(cast<FunctionDecl>(D));
2655 }
2656 return LOLR_Error;
2657 }
2658
2659 if (FoundRaw)
2660 return LOLR_Raw;
2661
2662 if (FoundTemplate)
2663 return LOLR_Template;
2664
2665 // Didn't find anything we could use.
2666 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2667 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2668 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2669 return LOLR_Error;
2670}
2671
John McCall7edb5fd2010-01-26 07:16:45 +00002672void ADLResult::insert(NamedDecl *New) {
2673 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2674
2675 // If we haven't yet seen a decl for this key, or the last decl
2676 // was exactly this one, we're done.
2677 if (Old == 0 || Old == New) {
2678 Old = New;
2679 return;
2680 }
2681
2682 // Otherwise, decide which is a more recent redeclaration.
2683 FunctionDecl *OldFD, *NewFD;
2684 if (isa<FunctionTemplateDecl>(New)) {
2685 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2686 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2687 } else {
2688 OldFD = cast<FunctionDecl>(Old);
2689 NewFD = cast<FunctionDecl>(New);
2690 }
2691
2692 FunctionDecl *Cursor = NewFD;
2693 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002694 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002695
2696 // If we got to the end without finding OldFD, OldFD is the newer
2697 // declaration; leave things as they are.
2698 if (!Cursor) return;
2699
2700 // If we do find OldFD, then NewFD is newer.
2701 if (Cursor == OldFD) break;
2702
2703 // Otherwise, keep looking.
2704 }
2705
2706 Old = New;
2707}
2708
Sebastian Redl644be852009-10-23 19:23:15 +00002709void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00002710 SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002711 llvm::ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002712 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002713 // Find all of the associated namespaces and classes based on the
2714 // arguments we have.
2715 AssociatedNamespaceSet AssociatedNamespaces;
2716 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002717 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002718 AssociatedNamespaces,
2719 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002720
Sebastian Redl644be852009-10-23 19:23:15 +00002721 QualType T1, T2;
2722 if (Operator) {
2723 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002724 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002725 T2 = Args[1]->getType();
2726 }
2727
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002728 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002729 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2730 // and let Y be the lookup set produced by argument dependent
2731 // lookup (defined as follows). If X contains [...] then Y is
2732 // empty. Otherwise Y is the set of declarations found in the
2733 // namespaces associated with the argument types as described
2734 // below. The set of declarations found by the lookup of the name
2735 // is the union of X and Y.
2736 //
2737 // Here, we compute Y and add its members to the overloaded
2738 // candidate set.
2739 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002740 NSEnd = AssociatedNamespaces.end();
2741 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002742 // When considering an associated namespace, the lookup is the
2743 // same as the lookup performed when the associated namespace is
2744 // used as a qualifier (3.4.3.2) except that:
2745 //
2746 // -- Any using-directives in the associated namespace are
2747 // ignored.
2748 //
John McCall6ff07852009-08-07 22:18:02 +00002749 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002750 // associated classes are visible within their respective
2751 // namespaces even if they are not visible during an ordinary
2752 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002753 DeclContext::lookup_result R = (*NS)->lookup(Name);
2754 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2755 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002756 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002757 // If the only declaration here is an ordinary friend, consider
2758 // it only if it was declared in an associated classes.
2759 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002760 DeclContext *LexDC = D->getLexicalDeclContext();
2761 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2762 continue;
2763 }
Mike Stump1eb44332009-09-09 15:08:12 +00002764
John McCalla113e722010-01-26 06:04:06 +00002765 if (isa<UsingShadowDecl>(D))
2766 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002767
John McCalla113e722010-01-26 06:04:06 +00002768 if (isa<FunctionDecl>(D)) {
2769 if (Operator &&
2770 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2771 T1, T2, Context))
2772 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002773 } else if (!isa<FunctionTemplateDecl>(D))
2774 continue;
2775
2776 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002777 }
2778 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002779}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002780
2781//----------------------------------------------------------------------------
2782// Search for all visible declarations.
2783//----------------------------------------------------------------------------
2784VisibleDeclConsumer::~VisibleDeclConsumer() { }
2785
2786namespace {
2787
2788class ShadowContextRAII;
2789
2790class VisibleDeclsRecord {
2791public:
2792 /// \brief An entry in the shadow map, which is optimized to store a
2793 /// single declaration (the common case) but can also store a list
2794 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002795 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002796
2797private:
2798 /// \brief A mapping from declaration names to the declarations that have
2799 /// this name within a particular scope.
2800 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2801
2802 /// \brief A list of shadow maps, which is used to model name hiding.
2803 std::list<ShadowMap> ShadowMaps;
2804
2805 /// \brief The declaration contexts we have already visited.
2806 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2807
2808 friend class ShadowContextRAII;
2809
2810public:
2811 /// \brief Determine whether we have already visited this context
2812 /// (and, if not, note that we are going to visit that context now).
2813 bool visitedContext(DeclContext *Ctx) {
2814 return !VisitedContexts.insert(Ctx);
2815 }
2816
Douglas Gregor8071e422010-08-15 06:18:01 +00002817 bool alreadyVisitedContext(DeclContext *Ctx) {
2818 return VisitedContexts.count(Ctx);
2819 }
2820
Douglas Gregor546be3c2009-12-30 17:04:44 +00002821 /// \brief Determine whether the given declaration is hidden in the
2822 /// current scope.
2823 ///
2824 /// \returns the declaration that hides the given declaration, or
2825 /// NULL if no such declaration exists.
2826 NamedDecl *checkHidden(NamedDecl *ND);
2827
2828 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002829 void add(NamedDecl *ND) {
2830 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2831 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002832};
2833
2834/// \brief RAII object that records when we've entered a shadow context.
2835class ShadowContextRAII {
2836 VisibleDeclsRecord &Visible;
2837
2838 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2839
2840public:
2841 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2842 Visible.ShadowMaps.push_back(ShadowMap());
2843 }
2844
2845 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002846 Visible.ShadowMaps.pop_back();
2847 }
2848};
2849
2850} // end anonymous namespace
2851
Douglas Gregor546be3c2009-12-30 17:04:44 +00002852NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002853 // Look through using declarations.
2854 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002855
Douglas Gregor546be3c2009-12-30 17:04:44 +00002856 unsigned IDNS = ND->getIdentifierNamespace();
2857 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2858 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2859 SM != SMEnd; ++SM) {
2860 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2861 if (Pos == SM->end())
2862 continue;
2863
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002864 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002865 IEnd = Pos->second.end();
2866 I != IEnd; ++I) {
2867 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002868 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002869 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002870 Decl::IDNS_ObjCProtocol)))
2871 continue;
2872
2873 // Protocols are in distinct namespaces from everything else.
2874 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2875 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2876 (*I)->getIdentifierNamespace() != IDNS)
2877 continue;
2878
Douglas Gregor0cc84042010-01-14 15:47:35 +00002879 // Functions and function templates in the same scope overload
2880 // rather than hide. FIXME: Look for hiding based on function
2881 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002882 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002883 ND->isFunctionOrFunctionTemplate() &&
2884 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002885 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002886
Douglas Gregor546be3c2009-12-30 17:04:44 +00002887 // We've found a declaration that hides this one.
2888 return *I;
2889 }
2890 }
2891
2892 return 0;
2893}
2894
2895static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2896 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002897 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002898 VisibleDeclConsumer &Consumer,
2899 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002900 if (!Ctx)
2901 return;
2902
Douglas Gregor546be3c2009-12-30 17:04:44 +00002903 // Make sure we don't visit the same context twice.
2904 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2905 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002906
Douglas Gregor4923aa22010-07-02 20:37:36 +00002907 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2908 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2909
Douglas Gregor546be3c2009-12-30 17:04:44 +00002910 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00002911 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2912 LEnd = Ctx->lookups_end();
2913 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002914 DeclContext::lookup_result R = *L;
2915 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2916 ++I) {
2917 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00002918 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002919 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002920 Visited.add(ND);
2921 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002922 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002923 }
2924 }
2925
2926 // Traverse using directives for qualified name lookup.
2927 if (QualifiedNameLookup) {
2928 ShadowContextRAII Shadow(Visited);
2929 DeclContext::udir_iterator I, E;
2930 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002931 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002932 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002933 }
2934 }
2935
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002936 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002937 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002938 if (!Record->hasDefinition())
2939 return;
2940
Douglas Gregor546be3c2009-12-30 17:04:44 +00002941 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2942 BEnd = Record->bases_end();
2943 B != BEnd; ++B) {
2944 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002945
Douglas Gregor546be3c2009-12-30 17:04:44 +00002946 // Don't look into dependent bases, because name lookup can't look
2947 // there anyway.
2948 if (BaseType->isDependentType())
2949 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002950
Douglas Gregor546be3c2009-12-30 17:04:44 +00002951 const RecordType *Record = BaseType->getAs<RecordType>();
2952 if (!Record)
2953 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002954
Douglas Gregor546be3c2009-12-30 17:04:44 +00002955 // FIXME: It would be nice to be able to determine whether referencing
2956 // a particular member would be ambiguous. For example, given
2957 //
2958 // struct A { int member; };
2959 // struct B { int member; };
2960 // struct C : A, B { };
2961 //
2962 // void f(C *c) { c->### }
2963 //
2964 // accessing 'member' would result in an ambiguity. However, we
2965 // could be smart enough to qualify the member with the base
2966 // class, e.g.,
2967 //
2968 // c->B::member
2969 //
2970 // or
2971 //
2972 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002973
Douglas Gregor546be3c2009-12-30 17:04:44 +00002974 // Find results in this base class (and its bases).
2975 ShadowContextRAII Shadow(Visited);
2976 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002977 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002978 }
2979 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002980
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002981 // Traverse the contexts of Objective-C classes.
2982 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2983 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00002984 for (ObjCInterfaceDecl::visible_categories_iterator
2985 Cat = IFace->visible_categories_begin(),
2986 CatEnd = IFace->visible_categories_end();
2987 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002988 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00002989 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002990 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002991 }
2992
2993 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002994 for (ObjCInterfaceDecl::all_protocol_iterator
2995 I = IFace->all_referenced_protocol_begin(),
2996 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002997 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
3002 // Traverse the superclass.
3003 if (IFace->getSuperClass()) {
3004 ShadowContextRAII Shadow(Visited);
3005 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003006 true, Consumer, 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. We do this to find
3010 // synthesized ivars.
3011 if (IFace->getImplementation()) {
3012 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003013 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00003014 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00003015 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003016 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3017 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3018 E = Protocol->protocol_end(); I != E; ++I) {
3019 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003020 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003021 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003022 }
3023 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3024 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3025 E = Category->protocol_end(); I != E; ++I) {
3026 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003027 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003028 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003029 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003030
Douglas Gregorc220a182010-04-19 18:02:19 +00003031 // If there is an implementation, traverse it.
3032 if (Category->getImplementation()) {
3033 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003034 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00003035 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003036 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003037 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003038}
3039
3040static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3041 UnqualUsingDirectiveSet &UDirs,
3042 VisibleDeclConsumer &Consumer,
3043 VisibleDeclsRecord &Visited) {
3044 if (!S)
3045 return;
3046
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003047 if (!S->getEntity() ||
3048 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00003049 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00003050 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3051 // Walk through the declarations in this Scope.
3052 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3053 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003054 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003055 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003056 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003057 Visited.add(ND);
3058 }
3059 }
3060 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003061
Douglas Gregor711be1e2010-03-15 14:33:29 +00003062 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003063 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003064 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003065 // Look into this scope's declaration context, along with any of its
3066 // parent lookup contexts (e.g., enclosing classes), up to the point
3067 // where we hit the context stored in the next outer scope.
3068 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003069 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003070
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003071 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003072 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003073 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3074 if (Method->isInstanceMethod()) {
3075 // For instance methods, look for ivars in the method's interface.
3076 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3077 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003078 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003079 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00003080 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003081 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003082 }
3083
3084 // We've already performed all of the name lookup that we need
3085 // to for Objective-C methods; the next context will be the
3086 // outer scope.
3087 break;
3088 }
3089
Douglas Gregor546be3c2009-12-30 17:04:44 +00003090 if (Ctx->isFunctionOrMethod())
3091 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003092
3093 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003094 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003095 }
3096 } else if (!S->getParent()) {
3097 // Look into the translation unit scope. We walk through the translation
3098 // unit's declaration context, because the Scope itself won't have all of
3099 // the declarations if we loaded a precompiled header.
3100 // FIXME: We would like the translation unit's Scope object to point to the
3101 // translation unit, so we don't need this special "if" branch. However,
3102 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003103 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003104 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003105 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003106 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003107 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003108 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003109 }
3110
Douglas Gregor546be3c2009-12-30 17:04:44 +00003111 if (Entity) {
3112 // Lookup visible declarations in any namespaces found by using
3113 // directives.
3114 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3115 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3116 for (; UI != UEnd; ++UI)
3117 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003118 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003119 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003120 }
3121
3122 // Lookup names in the parent scope.
3123 ShadowContextRAII Shadow(Visited);
3124 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3125}
3126
3127void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003128 VisibleDeclConsumer &Consumer,
3129 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003130 // Determine the set of using directives available during
3131 // unqualified name lookup.
3132 Scope *Initial = S;
3133 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003134 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003135 // Find the first namespace or translation-unit scope.
3136 while (S && !isNamespaceOrTranslationUnitScope(S))
3137 S = S->getParent();
3138
3139 UDirs.visitScopeChain(Initial, S);
3140 }
3141 UDirs.done();
3142
3143 // Look for visible declarations.
3144 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3145 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003146 if (!IncludeGlobalScope)
3147 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003148 ShadowContextRAII Shadow(Visited);
3149 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3150}
3151
3152void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003153 VisibleDeclConsumer &Consumer,
3154 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003155 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3156 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003157 if (!IncludeGlobalScope)
3158 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003159 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003160 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003161 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003162}
3163
Chris Lattner4ae493c2011-02-18 02:08:43 +00003164/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003165/// If GnuLabelLoc is a valid source location, then this is a definition
3166/// of an __label__ label name, otherwise it is a normal label definition
3167/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003168LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003169 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003170 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003171 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003172
3173 if (GnuLabelLoc.isValid()) {
3174 // Local label definitions always shadow existing labels.
3175 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3176 Scope *S = CurScope;
3177 PushOnScopeChains(Res, S, true);
3178 return cast<LabelDecl>(Res);
3179 }
3180
3181 // Not a GNU local label.
3182 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3183 // If we found a label, check to see if it is in the same context as us.
3184 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003185 if (Res && Res->getDeclContext() != CurContext)
3186 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003187 if (Res == 0) {
3188 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003189 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3190 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003191 assert(S && "Not in a function?");
3192 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003193 }
Chris Lattner337e5502011-02-18 01:27:55 +00003194 return cast<LabelDecl>(Res);
3195}
3196
3197//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003198// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003199//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003200
3201namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003202
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003203typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003204typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003205typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003206
3207static const unsigned MaxTypoDistanceResultSets = 5;
3208
Douglas Gregor546be3c2009-12-30 17:04:44 +00003209class TypoCorrectionConsumer : public VisibleDeclConsumer {
3210 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003211 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003212
3213 /// \brief The results found that have the smallest edit distance
3214 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003215 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003216 /// The pointer value being set to the current DeclContext indicates
3217 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003218 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003219
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003220 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003221
Douglas Gregor546be3c2009-12-30 17:04:44 +00003222public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003223 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003224 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003225 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003226
Erik Verbruggend1205962011-10-06 07:27:49 +00003227 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3228 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003229 void FoundName(StringRef Name);
3230 void addKeywordResult(StringRef Keyword);
3231 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003232 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003233 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003234
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003235 typedef TypoResultsMap::iterator result_iterator;
3236 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003237 distance_iterator begin() { return CorrectionResults.begin(); }
3238 distance_iterator end() { return CorrectionResults.end(); }
3239 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3240 unsigned size() const { return CorrectionResults.size(); }
3241 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003242
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003243 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003244 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003245 }
3246
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003247 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003248 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003249 return (std::numeric_limits<unsigned>::max)();
3250
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003251 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003252 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003253 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003254
3255 TypoResultsMap &getBestResults() {
3256 return CorrectionResults.begin()->second;
3257 }
3258
Douglas Gregor546be3c2009-12-30 17:04:44 +00003259};
3260
3261}
3262
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003264 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003265 // Don't consider hidden names for typo correction.
3266 if (Hiding)
3267 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003268
Douglas Gregor546be3c2009-12-30 17:04:44 +00003269 // Only consider entities with identifiers for names, ignoring
3270 // special names (constructors, overloaded operators, selectors,
3271 // etc.).
3272 IdentifierInfo *Name = ND->getIdentifier();
3273 if (!Name)
3274 return;
3275
Douglas Gregor95f42922010-10-14 22:11:03 +00003276 FoundName(Name->getName());
3277}
3278
Chris Lattner5f9e2722011-07-23 10:55:15 +00003279void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003280 // Use a simple length-based heuristic to determine the minimum possible
3281 // edit distance. If the minimum isn't good enough, bail out early.
3282 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003283 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003284 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003285
Douglas Gregora1194772010-10-19 22:14:33 +00003286 // Compute an upper bound on the allowable edit distance, so that the
3287 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003288 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003289
Douglas Gregor546be3c2009-12-30 17:04:44 +00003290 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003291 // entity, and add the identifier to the list of results.
3292 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003293}
3294
Chris Lattner5f9e2722011-07-23 10:55:15 +00003295void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003296 // Compute the edit distance between the typo and this keyword,
3297 // and add the keyword to the list of results.
3298 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003299}
3300
Chris Lattner5f9e2722011-07-23 10:55:15 +00003301void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003302 NamedDecl *ND,
3303 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003304 NestedNameSpecifier *NNS,
3305 bool isKeyword) {
3306 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3307 if (isKeyword) TC.makeKeyword();
3308 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003309}
3310
3311void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003312 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003313 TypoResultList &CList =
3314 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003315
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003316 if (!CList.empty() && !CList.back().isResolved())
3317 CList.pop_back();
3318 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3319 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3320 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3321 RI != RIEnd; ++RI) {
3322 // If the Correction refers to a decl already in the result list,
3323 // replace the existing result if the string representation of Correction
3324 // comes before the current result alphabetically, then stop as there is
3325 // nothing more to be done to add Correction to the candidate set.
3326 if (RI->getCorrectionDecl() == NewND) {
3327 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3328 *RI = Correction;
3329 return;
3330 }
3331 }
3332 }
3333 if (CList.empty() || Correction.isResolved())
3334 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003335
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003336 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3337 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003338}
3339
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003340// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3341// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3342// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3343static void getNestedNameSpecifierIdentifiers(
3344 NestedNameSpecifier *NNS,
3345 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3346 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3347 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3348 else
3349 Identifiers.clear();
3350
3351 const IdentifierInfo *II = NULL;
3352
3353 switch (NNS->getKind()) {
3354 case NestedNameSpecifier::Identifier:
3355 II = NNS->getAsIdentifier();
3356 break;
3357
3358 case NestedNameSpecifier::Namespace:
3359 if (NNS->getAsNamespace()->isAnonymousNamespace())
3360 return;
3361 II = NNS->getAsNamespace()->getIdentifier();
3362 break;
3363
3364 case NestedNameSpecifier::NamespaceAlias:
3365 II = NNS->getAsNamespaceAlias()->getIdentifier();
3366 break;
3367
3368 case NestedNameSpecifier::TypeSpecWithTemplate:
3369 case NestedNameSpecifier::TypeSpec:
3370 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3371 break;
3372
3373 case NestedNameSpecifier::Global:
3374 return;
3375 }
3376
3377 if (II)
3378 Identifiers.push_back(II);
3379}
3380
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003381namespace {
3382
3383class SpecifierInfo {
3384 public:
3385 DeclContext* DeclCtx;
3386 NestedNameSpecifier* NameSpecifier;
3387 unsigned EditDistance;
3388
3389 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3390 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3391};
3392
Chris Lattner5f9e2722011-07-23 10:55:15 +00003393typedef SmallVector<DeclContext*, 4> DeclContextList;
3394typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003395
3396class NamespaceSpecifierSet {
3397 ASTContext &Context;
3398 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003399 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3400 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003401 bool isSorted;
3402
3403 SpecifierInfoList Specifiers;
3404 llvm::SmallSetVector<unsigned, 4> Distances;
3405 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3406
3407 /// \brief Helper for building the list of DeclContexts between the current
3408 /// context and the top of the translation unit
3409 static DeclContextList BuildContextChain(DeclContext *Start);
3410
3411 void SortNamespaces();
3412
3413 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003414 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3415 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003416 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003417 isSorted(true) {
3418 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3419 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3420 CurNameSpecifierIdentifiers);
3421 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003422 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003423 // context.
3424 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3425 CEnd = CurContextChain.rend();
3426 C != CEnd; ++C) {
3427 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3428 CurContextIdentifiers.push_back(ND->getIdentifier());
3429 }
3430 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003431
3432 /// \brief Add the namespace to the set, computing the corresponding
3433 /// NestedNameSpecifier and its distance in the process.
3434 void AddNamespace(NamespaceDecl *ND);
3435
3436 typedef SpecifierInfoList::iterator iterator;
3437 iterator begin() {
3438 if (!isSorted) SortNamespaces();
3439 return Specifiers.begin();
3440 }
3441 iterator end() { return Specifiers.end(); }
3442};
3443
3444}
3445
3446DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0db9d202013-04-08 21:55:21 +00003447 assert(Start && "Building a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003448 DeclContextList Chain;
3449 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3450 DC = DC->getLookupParent()) {
3451 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3452 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3453 !(ND && ND->isAnonymousNamespace()))
3454 Chain.push_back(DC->getPrimaryContext());
3455 }
3456 return Chain;
3457}
3458
3459void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003460 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003461 sortedDistances.append(Distances.begin(), Distances.end());
3462
3463 if (sortedDistances.size() > 1)
3464 std::sort(sortedDistances.begin(), sortedDistances.end());
3465
3466 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003467 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003468 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003469 DI != DIEnd; ++DI) {
3470 SpecifierInfoList &SpecList = DistanceMap[*DI];
3471 Specifiers.append(SpecList.begin(), SpecList.end());
3472 }
3473
3474 isSorted = true;
3475}
3476
3477void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003478 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003479 NestedNameSpecifier *NNS = NULL;
3480 unsigned NumSpecifiers = 0;
3481 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003482 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003483
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003484 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003485 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3486 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003487 C != CEnd && !NamespaceDeclChain.empty() &&
3488 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003489 NamespaceDeclChain.pop_back();
3490 }
3491
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003492 // Add an explicit leading '::' specifier if needed.
3493 if (NamespaceDecl *ND =
Kaelyn Uhrain3ad02aa2012-02-15 22:59:03 +00003494 NamespaceDeclChain.empty() ? NULL :
3495 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003496 IdentifierInfo *Name = ND->getIdentifier();
3497 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3498 Name) != CurContextIdentifiers.end() ||
3499 std::find(CurNameSpecifierIdentifiers.begin(),
3500 CurNameSpecifierIdentifiers.end(),
3501 Name) != CurNameSpecifierIdentifiers.end()) {
3502 NamespaceDeclChain = FullNamespaceDeclChain;
3503 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3504 }
3505 }
3506
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003507 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3508 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3509 CEnd = NamespaceDeclChain.rend();
3510 C != CEnd; ++C) {
3511 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3512 if (ND) {
3513 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3514 ++NumSpecifiers;
3515 }
3516 }
3517
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003518 // If the built NestedNameSpecifier would be replacing an existing
3519 // NestedNameSpecifier, use the number of component identifiers that
3520 // would need to be changed as the edit distance instead of the number
3521 // of components in the built NestedNameSpecifier.
3522 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3523 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3524 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3525 NumSpecifiers = llvm::ComputeEditDistance(
3526 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3527 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3528 }
3529
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003530 isSorted = false;
3531 Distances.insert(NumSpecifiers);
3532 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003533}
3534
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003535/// \brief Perform name lookup for a possible result for typo correction.
3536static void LookupPotentialTypoResult(Sema &SemaRef,
3537 LookupResult &Res,
3538 IdentifierInfo *Name,
3539 Scope *S, CXXScopeSpec *SS,
3540 DeclContext *MemberContext,
3541 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003542 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003543 Res.suppressDiagnostics();
3544 Res.clear();
3545 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003546 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003547 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003548 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003549 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3550 Res.addDecl(Ivar);
3551 Res.resolveKind();
3552 return;
3553 }
3554 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003555
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003556 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3557 Res.addDecl(Prop);
3558 Res.resolveKind();
3559 return;
3560 }
3561 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003562
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003563 SemaRef.LookupQualifiedName(Res, MemberContext);
3564 return;
3565 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003566
3567 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003568 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003569
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003570 // Fake ivar lookup; this should really be part of
3571 // LookupParsedName.
3572 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3573 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003574 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003575 (Res.isSingleResult() &&
3576 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003577 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003578 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3579 Res.addDecl(IV);
3580 Res.resolveKind();
3581 }
3582 }
3583 }
3584}
3585
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003586/// \brief Add keywords to the consumer as possible typo corrections.
3587static void AddKeywordsToConsumer(Sema &SemaRef,
3588 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003589 Scope *S, CorrectionCandidateCallback &CCC,
3590 bool AfterNestedNameSpecifier) {
3591 if (AfterNestedNameSpecifier) {
3592 // For 'X::', we know exactly which keywords can appear next.
3593 Consumer.addKeywordResult("template");
3594 if (CCC.WantExpressionKeywords)
3595 Consumer.addKeywordResult("operator");
3596 return;
3597 }
3598
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003599 if (CCC.WantObjCSuper)
3600 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003601
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003602 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003603 // Add type-specifier keywords to the set of results.
3604 const char *CTypeSpecs[] = {
3605 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003606 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003607 "_Complex", "_Imaginary",
3608 // storage-specifiers as well
3609 "extern", "inline", "static", "typedef"
3610 };
3611
3612 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3613 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3614 Consumer.addKeywordResult(CTypeSpecs[I]);
3615
David Blaikie4e4d0842012-03-11 07:00:24 +00003616 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003617 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003618 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003619 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003620 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003621 Consumer.addKeywordResult("_Bool");
3622
David Blaikie4e4d0842012-03-11 07:00:24 +00003623 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003624 Consumer.addKeywordResult("class");
3625 Consumer.addKeywordResult("typename");
3626 Consumer.addKeywordResult("wchar_t");
3627
Richard Smith80ad52f2013-01-02 11:42:31 +00003628 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003629 Consumer.addKeywordResult("char16_t");
3630 Consumer.addKeywordResult("char32_t");
3631 Consumer.addKeywordResult("constexpr");
3632 Consumer.addKeywordResult("decltype");
3633 Consumer.addKeywordResult("thread_local");
3634 }
3635 }
3636
David Blaikie4e4d0842012-03-11 07:00:24 +00003637 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003638 Consumer.addKeywordResult("typeof");
3639 }
3640
David Blaikie4e4d0842012-03-11 07:00:24 +00003641 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003642 Consumer.addKeywordResult("const_cast");
3643 Consumer.addKeywordResult("dynamic_cast");
3644 Consumer.addKeywordResult("reinterpret_cast");
3645 Consumer.addKeywordResult("static_cast");
3646 }
3647
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003648 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003649 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003650 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003651 Consumer.addKeywordResult("false");
3652 Consumer.addKeywordResult("true");
3653 }
3654
David Blaikie4e4d0842012-03-11 07:00:24 +00003655 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003656 const char *CXXExprs[] = {
3657 "delete", "new", "operator", "throw", "typeid"
3658 };
3659 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3660 for (unsigned I = 0; I != NumCXXExprs; ++I)
3661 Consumer.addKeywordResult(CXXExprs[I]);
3662
3663 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3664 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3665 Consumer.addKeywordResult("this");
3666
Richard Smith80ad52f2013-01-02 11:42:31 +00003667 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003668 Consumer.addKeywordResult("alignof");
3669 Consumer.addKeywordResult("nullptr");
3670 }
3671 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003672
3673 if (SemaRef.getLangOpts().C11) {
3674 // FIXME: We should not suggest _Alignof if the alignof macro
3675 // is present.
3676 Consumer.addKeywordResult("_Alignof");
3677 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003678 }
3679
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003680 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003681 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3682 // Statements.
3683 const char *CStmts[] = {
3684 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3685 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3686 for (unsigned I = 0; I != NumCStmts; ++I)
3687 Consumer.addKeywordResult(CStmts[I]);
3688
David Blaikie4e4d0842012-03-11 07:00:24 +00003689 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003690 Consumer.addKeywordResult("catch");
3691 Consumer.addKeywordResult("try");
3692 }
3693
3694 if (S && S->getBreakParent())
3695 Consumer.addKeywordResult("break");
3696
3697 if (S && S->getContinueParent())
3698 Consumer.addKeywordResult("continue");
3699
3700 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3701 Consumer.addKeywordResult("case");
3702 Consumer.addKeywordResult("default");
3703 }
3704 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003705 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003706 Consumer.addKeywordResult("namespace");
3707 Consumer.addKeywordResult("template");
3708 }
3709
3710 if (S && S->isClassScope()) {
3711 Consumer.addKeywordResult("explicit");
3712 Consumer.addKeywordResult("friend");
3713 Consumer.addKeywordResult("mutable");
3714 Consumer.addKeywordResult("private");
3715 Consumer.addKeywordResult("protected");
3716 Consumer.addKeywordResult("public");
3717 Consumer.addKeywordResult("virtual");
3718 }
3719 }
3720
David Blaikie4e4d0842012-03-11 07:00:24 +00003721 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003722 Consumer.addKeywordResult("using");
3723
Richard Smith80ad52f2013-01-02 11:42:31 +00003724 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003725 Consumer.addKeywordResult("static_assert");
3726 }
3727 }
3728}
3729
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003730static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3731 TypoCorrection &Candidate) {
3732 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3733 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3734}
3735
Douglas Gregor546be3c2009-12-30 17:04:44 +00003736/// \brief Try to "correct" a typo in the source code by finding
3737/// visible declarations whose names are similar to the name that was
3738/// present in the source code.
3739///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003740/// \param TypoName the \c DeclarationNameInfo structure that contains
3741/// the name that was present in the source code along with its location.
3742///
3743/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003744///
3745/// \param S the scope in which name lookup occurs.
3746///
3747/// \param SS the nested-name-specifier that precedes the name we're
3748/// looking for, if present.
3749///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003750/// \param CCC A CorrectionCandidateCallback object that provides further
3751/// validation of typo correction candidates. It also provides flags for
3752/// determining the set of keywords permitted.
3753///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003754/// \param MemberContext if non-NULL, the context in which to look for
3755/// a member access expression.
3756///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003757/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003758/// the nested-name-specifier SS.
3759///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003760/// \param OPT when non-NULL, the search for visible declarations will
3761/// also walk the protocols in the qualified interfaces of \p OPT.
3762///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003763/// \returns a \c TypoCorrection containing the corrected name if the typo
3764/// along with information such as the \c NamedDecl where the corrected name
3765/// was declared, and any additional \c NestedNameSpecifier needed to access
3766/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3767TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3768 Sema::LookupNameKind LookupKind,
3769 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003770 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003771 DeclContext *MemberContext,
3772 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003773 const ObjCObjectPointerType *OPT) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003774 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003775 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003776
Francois Pichet4d604d62011-12-03 15:55:29 +00003777 // In Microsoft mode, don't perform typo correction in a template member
3778 // function dependent context because it interferes with the "lookup into
3779 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003780 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003781 isa<CXXMethodDecl>(CurContext))
3782 return TypoCorrection();
3783
Douglas Gregor546be3c2009-12-30 17:04:44 +00003784 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003785 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003786 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003787 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003788
3789 // If the scope specifier itself was invalid, don't try to correct
3790 // typos.
3791 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003792 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003793
3794 // Never try to correct typos during template deduction or
3795 // instantiation.
3796 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003797 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003798
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003799 // Don't try to correct 'super'.
3800 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3801 return TypoCorrection();
3802
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003803 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003804
3805 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003807 // If a callback object considers an empty typo correction candidate to be
3808 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003809 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003810 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003811
Douglas Gregoraaf87162010-04-14 20:04:41 +00003812 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003813 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003814 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003815 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003816 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003817
3818 // Look in qualified interfaces.
3819 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003820 for (ObjCObjectPointerType::qual_iterator
3821 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003822 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003823 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003824 }
3825 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003826 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3827 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003828 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003829
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003830 // Provide a stop gap for files that are just seriously broken. Trying
3831 // to correct all typos can turn into a HUGE performance penalty, causing
3832 // some files to take minutes to get rejected by the parser.
3833 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003834 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003835 ++TyposCorrected;
3836
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003837 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003838 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003839 IsUnqualifiedLookup = true;
3840 UnqualifiedTyposCorrectedMap::iterator Cached
3841 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003842 if (Cached != UnqualifiedTyposCorrected.end()) {
3843 // Add the cached value, unless it's a keyword or fails validation. In the
3844 // keyword case, we'll end up adding the keyword below.
3845 if (Cached->second) {
3846 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003847 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003848 Consumer.addCorrection(Cached->second);
3849 } else {
3850 // Only honor no-correction cache hits when a callback that will validate
3851 // correction candidates is not being used.
3852 if (!ValidatingCallback)
3853 return TypoCorrection();
3854 }
3855 }
3856 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003857 // Provide a stop gap for files that are just seriously broken. Trying
3858 // to correct all typos can turn into a HUGE performance penalty, causing
3859 // some files to take minutes to get rejected by the parser.
3860 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003861 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003862 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003863 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003864
Douglas Gregor01798682012-03-26 16:54:18 +00003865 // Determine whether we are going to search in the various namespaces for
3866 // corrections.
3867 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00003868 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00003869 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003870 // In a few cases we *only* want to search for corrections bases on just
3871 // adding or changing the nested name specifier.
3872 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00003873
3874 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003875 // For unqualified lookup, look through all of the names that we have
3876 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003877 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003878 for (IdentifierTable::iterator I = Context.Idents.begin(),
3879 IEnd = Context.Idents.end();
3880 I != IEnd; ++I)
3881 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003882
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003883 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003884 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003885 if (IdentifierInfoLookup *External
3886 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003887 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003888 do {
3889 StringRef Name = Iter->Next();
3890 if (Name.empty())
3891 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003892
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003893 Consumer.FoundName(Name);
3894 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00003895 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003896 }
3897
Richard Smith0f4b5be2012-06-08 21:35:42 +00003898 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003899
Douglas Gregoraaf87162010-04-14 20:04:41 +00003900 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003901 if (Consumer.empty()) {
3902 // If this was an unqualified lookup, note that no correction was found.
3903 if (IsUnqualifiedLookup)
3904 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003905
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003906 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003907 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003908
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003909 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3910 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003911 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003912 if (ED > 0 && Typo->getName().size() / ED < 3) {
3913 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003914 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003915 (void)UnqualifiedTyposCorrected[Typo];
3916
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003917 return TypoCorrection();
3918 }
3919
Douglas Gregor01798682012-03-26 16:54:18 +00003920 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3921 // to search those namespaces.
3922 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003923 // Load any externally-known namespaces.
3924 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003925 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003926 LoadedExternalKnownNamespaces = true;
3927 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3928 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3929 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3930 }
3931
Nick Lewycky01a41142013-01-26 00:35:08 +00003932 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003933 KNI = KnownNamespaces.begin(),
3934 KNIEnd = KnownNamespaces.end();
3935 KNI != KNIEnd; ++KNI)
3936 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003937 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003938
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003939 // Weed out any names that could not be found by name lookup or, if a
3940 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003941 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003942 LookupResult TmpRes(*this, TypoName, LookupKind);
3943 TmpRes.suppressDiagnostics();
3944 while (!Consumer.empty()) {
3945 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3946 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003947 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3948 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003949 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003950 // If we only want nested name specifier corrections, ignore potential
3951 // corrections that have a different base identifier from the typo.
3952 if (AllowOnlyNNSChanges &&
3953 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3954 TypoCorrectionConsumer::result_iterator Prev = I;
3955 ++I;
3956 DI->second.erase(Prev);
3957 continue;
3958 }
3959
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003960 // If the item already has been looked up or is a keyword, keep it.
3961 // If a validator callback object was given, drop the correction
3962 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003963 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00003964 for (TypoResultList::iterator RI = I->second.begin();
3965 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003966 TypoResultList::iterator Prev = RI;
3967 ++RI;
3968 if (Prev->isResolved()) {
3969 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00003970 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003971 else
3972 Viable = true;
3973 }
3974 }
3975 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003976 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003977 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003978 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003979 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003980 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003981 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003982 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003983
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003984 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003985 TypoCorrection &Candidate = I->second.front();
3986 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003987 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003988 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003989
3990 switch (TmpRes.getResultKind()) {
3991 case LookupResult::NotFound:
3992 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003993 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003994 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003995 // We didn't find this name in our scope, or didn't like what we found;
3996 // ignore it.
3997 {
3998 TypoCorrectionConsumer::result_iterator Next = I;
3999 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004000 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004001 I = Next;
4002 }
4003 break;
4004
4005 case LookupResult::Ambiguous:
4006 // We don't deal with ambiguities.
4007 return TypoCorrection();
4008
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004009 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004010 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004011 // Store all of the Decls for overloaded symbols
4012 for (LookupResult::iterator TRD = TmpRes.begin(),
4013 TRDEnd = TmpRes.end();
4014 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004015 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004016 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004017 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004018 DI->second.erase(Prev);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004019 break;
4020 }
4021
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004022 case LookupResult::Found: {
4023 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004024 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004025 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004026 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004027 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004028 break;
4029 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004030
4031 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004032 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004033
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004034 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004035 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00004036 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004037 // If there are results in the closest possible bucket, stop
4038 break;
4039
4040 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004041 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004042 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004043 for (SmallVector<TypoCorrection,
4044 16>::iterator QRI = QualifiedResults.begin(),
4045 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004046 QRI != QRIEnd; ++QRI) {
4047 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4048 NIEnd = Namespaces.end();
4049 NI != NIEnd; ++NI) {
4050 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004051
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004052 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004053 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004054 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004055
4056 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004057 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004058 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4059
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004060 // Any corrections added below will be validated in subsequent
4061 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004062 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004063 case LookupResult::Found: {
4064 TypoCorrection TC(*QRI);
4065 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
4066 TC.setCorrectionSpecifier(NI->NameSpecifier);
4067 TC.setQualifierDistance(NI->EditDistance);
4068 Consumer.addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004069 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004070 }
4071 case LookupResult::FoundOverloaded: {
4072 TypoCorrection TC(*QRI);
4073 TC.setCorrectionSpecifier(NI->NameSpecifier);
4074 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004075 for (LookupResult::iterator TRD = TmpRes.begin(),
4076 TRDEnd = TmpRes.end();
4077 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004078 TC.addCorrectionDecl(*TRD);
4079 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004080 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004081 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004082 case LookupResult::NotFound:
4083 case LookupResult::NotFoundInCurrentInstantiation:
4084 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004085 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004086 break;
4087 }
4088 }
4089 }
4090 }
4091
4092 QualifiedResults.clear();
4093 }
4094
4095 // No corrections remain...
4096 if (Consumer.empty()) return TypoCorrection();
4097
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004098 TypoResultsMap &BestResults = Consumer.getBestResults();
4099 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004100
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004101 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004102 // If this was an unqualified lookup and we believe the callback
4103 // object wouldn't have filtered out possible corrections, note
4104 // that no correction was found.
4105 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004106 (void)UnqualifiedTyposCorrected[Typo];
4107
4108 return TypoCorrection();
4109 }
4110
Douglas Gregore24b5752010-10-14 20:34:08 +00004111 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004112 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004113 const TypoResultList &CorrectionList = BestResults.begin()->second;
4114 const TypoCorrection &Result = CorrectionList.front();
4115 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116
Douglas Gregor53e4b552010-10-26 17:18:00 +00004117 // Don't correct to a keyword that's the same as the typo; the keyword
4118 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004119 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4120
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004121 // Record the correction for unqualified lookup.
4122 if (IsUnqualifiedLookup)
4123 UnqualifiedTyposCorrected[Typo] = Result;
4124
David Blaikie6952c012012-10-12 20:00:44 +00004125 TypoCorrection TC = Result;
4126 TC.setCorrectionRange(SS, TypoName);
4127 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004128 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004129 else if (BestResults.size() > 1
4130 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4131 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4132 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4133 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004134 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004135 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004136 // Prefer 'super' when we're completing in a message-receiver
4137 // context.
4138
4139 // Don't correct to a keyword that's the same as the typo; the keyword
4140 // wasn't actually in scope.
4141 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004142
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004143 // Record the correction for unqualified lookup.
4144 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004145 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004146
David Blaikie6952c012012-10-12 20:00:44 +00004147 TypoCorrection TC = BestResults["super"].front();
4148 TC.setCorrectionRange(SS, TypoName);
4149 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004150 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004151
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004152 // If this was an unqualified lookup and we believe the callback object did
4153 // not filter out possible corrections, note that no correction was found.
4154 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004155 (void)UnqualifiedTyposCorrected[Typo];
4156
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004157 return TypoCorrection();
4158}
4159
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004160void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4161 if (!CDecl) return;
4162
4163 if (isKeyword())
4164 CorrectionDecls.clear();
4165
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004166 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004167
4168 if (!CorrectionName)
4169 CorrectionName = CDecl->getDeclName();
4170}
4171
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004172std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4173 if (CorrectionNameSpec) {
4174 std::string tmpBuffer;
4175 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4176 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikie17828ca2013-05-14 21:04:00 +00004177 PrefixOStream << CorrectionName;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004178 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004179 }
4180
4181 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004182}
Kaelyn Uhrain20a7cf42013-04-03 16:59:49 +00004183
4184bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4185 if (!candidate.isResolved())
4186 return true;
4187
4188 if (candidate.isKeyword())
4189 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4190 WantRemainingKeywords || WantObjCSuper;
4191
4192 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4193 CDeclEnd = candidate.end();
4194 CDecl != CDeclEnd; ++CDecl) {
4195 if (!isa<TypeDecl>(*CDecl))
4196 return true;
4197 }
4198
4199 return WantTypeSpecifiers;
4200}