blob: ded441cac682f3cf0ee66e263b4403c5719a072d [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/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
Sean Hunt308742c2011-06-04 04:32:43 +000017#include "clang/Sema/Overload.h"
John McCall19510852010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
John McCall5f1e0942010-08-24 08:50:51 +000019#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Axel Naumannf8291a12011-02-24 16:47:47 +000022#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregord8bba9c2011-06-28 16:20:02 +000023#include "clang/Sema/TypoCorrection.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000024#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000025#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000026#include "clang/AST/Decl.h"
27#include "clang/AST/DeclCXX.h"
Nick Lewycky173a37a2012-04-03 21:44:08 +000028#include "clang/AST/DeclLookups.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000029#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000030#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000031#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000032#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000034#include "clang/Basic/LangOptions.h"
Douglas Gregora1f21142012-02-01 17:04:21 +000035#include "llvm/ADT/SetVector.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000036#include "llvm/ADT/STLExtras.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
290 // If we're looking for one of the allocation or deallocation
291 // operators, make sure that the implicitly-declared new and delete
292 // operators can be found.
293 if (!isForRedeclaration()) {
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 }
305 }
John McCall1d7c5282009-12-18 10:40:03 +0000306}
307
Daniel Dunbarc2bd73b2012-03-08 01:43:06 +0000308void LookupResult::sanityImpl() const {
309 // Note that this function is never called by NDEBUG builds. See
310 // LookupResult::sanity().
John McCall2a7fb272010-08-25 05:32:35 +0000311 assert(ResultKind != NotFound || Decls.size() == 0);
312 assert(ResultKind != Found || Decls.size() == 1);
313 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
314 (Decls.size() == 1 &&
315 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
316 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
317 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000318 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
319 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000320 assert((Paths != NULL) == (ResultKind == Ambiguous &&
321 (Ambiguity == AmbiguousBaseSubobjectTypes ||
322 Ambiguity == AmbiguousBaseSubobjects)));
323}
John McCall2a7fb272010-08-25 05:32:35 +0000324
John McCallf36e02d2009-10-09 21:13:30 +0000325// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000326void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000327 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000328}
329
Douglas Gregor55368912011-12-14 16:03:29 +0000330static NamedDecl *getVisibleDecl(NamedDecl *D);
331
332NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
333 return getVisibleDecl(D);
334}
335
John McCall7453ed42009-11-22 00:44:51 +0000336/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000337void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000338 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000339
John McCallf36e02d2009-10-09 21:13:30 +0000340 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000341 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000342 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000343 return;
344 }
345
John McCall7453ed42009-11-22 00:44:51 +0000346 // If there's a single decl, we need to examine it to decide what
347 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000348 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000349 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
350 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000351 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000352 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000353 ResultKind = FoundUnresolvedValue;
354 return;
355 }
John McCallf36e02d2009-10-09 21:13:30 +0000356
John McCall6e247262009-10-10 05:48:19 +0000357 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000358 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000359
John McCallf36e02d2009-10-09 21:13:30 +0000360 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000361 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000362
John McCallf36e02d2009-10-09 21:13:30 +0000363 bool Ambiguous = false;
364 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000365 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000366
367 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000368
John McCallf36e02d2009-10-09 21:13:30 +0000369 unsigned I = 0;
370 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000371 NamedDecl *D = Decls[I]->getUnderlyingDecl();
372 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000373
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000374 // Redeclarations of types via typedef can occur both within a scope
375 // and, through using declarations and directives, across scopes. There is
376 // no ambiguity if they all refer to the same type, so unique based on the
377 // canonical type.
378 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
379 if (!TD->getDeclContext()->isRecord()) {
380 QualType T = SemaRef.Context.getTypeDeclType(TD);
381 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
382 // The type is not unique; pull something off the back and continue
383 // at this index.
384 Decls[I] = Decls[--N];
385 continue;
386 }
387 }
388 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000389
John McCall314be4e2009-11-17 07:50:12 +0000390 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000391 // If it's not unique, pull something off the back (and
392 // continue at this index).
393 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000394 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000395 }
396
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000397 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000398
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000399 if (isa<UnresolvedUsingValueDecl>(D)) {
400 HasUnresolved = true;
401 } else if (isa<TagDecl>(D)) {
402 if (HasTag)
403 Ambiguous = true;
404 UniqueTagIndex = I;
405 HasTag = true;
406 } else if (isa<FunctionTemplateDecl>(D)) {
407 HasFunction = true;
408 HasFunctionTemplate = true;
409 } else if (isa<FunctionDecl>(D)) {
410 HasFunction = true;
411 } else {
412 if (HasNonFunction)
413 Ambiguous = true;
414 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000415 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000416 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000417 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000418
John McCallf36e02d2009-10-09 21:13:30 +0000419 // C++ [basic.scope.hiding]p2:
420 // A class name or enumeration name can be hidden by the name of
421 // an object, function, or enumerator declared in the same
422 // scope. If a class or enumeration name and an object, function,
423 // or enumerator are declared in the same scope (in any order)
424 // with the same name, the class or enumeration name is hidden
425 // wherever the object, function, or enumerator name is visible.
426 // But it's still an error if there are distinct tag types found,
427 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000428 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000429 (HasFunction || HasNonFunction || HasUnresolved)) {
430 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
431 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
432 Decls[UniqueTagIndex] = Decls[--N];
433 else
434 Ambiguous = true;
435 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000436
John McCallf36e02d2009-10-09 21:13:30 +0000437 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000438
John McCallfda8e122009-12-03 00:58:24 +0000439 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000440 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000441
John McCallf36e02d2009-10-09 21:13:30 +0000442 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000443 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000444 else if (HasUnresolved)
445 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000446 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000447 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000448 else
John McCalla24dc2e2009-11-17 02:14:36 +0000449 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000450}
451
John McCall7d384dd2009-11-18 07:57:50 +0000452void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000453 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000454 DeclContext::lookup_iterator DI, DE;
455 for (I = P.begin(), E = P.end(); I != E; ++I)
456 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
457 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000458}
459
John McCall7d384dd2009-11-18 07:57:50 +0000460void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000461 Paths = new CXXBasePaths;
462 Paths->swap(P);
463 addDeclsFromBasePaths(*Paths);
464 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000465 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000466}
467
John McCall7d384dd2009-11-18 07:57:50 +0000468void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000469 Paths = new CXXBasePaths;
470 Paths->swap(P);
471 addDeclsFromBasePaths(*Paths);
472 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000473 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000474}
475
Chris Lattner5f9e2722011-07-23 10:55:15 +0000476void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000477 Out << Decls.size() << " result(s)";
478 if (isAmbiguous()) Out << ", ambiguous";
479 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000480
John McCallf36e02d2009-10-09 21:13:30 +0000481 for (iterator I = begin(), E = end(); I != E; ++I) {
482 Out << "\n";
483 (*I)->print(Out, 2);
484 }
485}
486
Douglas Gregor85910982010-02-12 05:48:04 +0000487/// \brief Lookup a builtin function, when name lookup would otherwise
488/// fail.
489static bool LookupBuiltin(Sema &S, LookupResult &R) {
490 Sema::LookupNameKind NameKind = R.getLookupKind();
491
492 // If we didn't find a use of this identifier, and if the identifier
493 // corresponds to a compiler builtin, create the decl object for the builtin
494 // now, injecting it into translation unit scope, and return it.
495 if (NameKind == Sema::LookupOrdinaryName ||
496 NameKind == Sema::LookupRedeclarationWithLinkage) {
497 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
498 if (II) {
499 // If this is a builtin on this (or all) targets, create the decl.
500 if (unsigned BuiltinID = II->getBuiltinID()) {
501 // In C++, we don't have any predefined library functions like
502 // 'malloc'. Instead, we'll just error.
David Blaikie4e4d0842012-03-11 07:00:24 +0000503 if (S.getLangOpts().CPlusPlus &&
Douglas Gregor85910982010-02-12 05:48:04 +0000504 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
505 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000506
507 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
508 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000509 R.isForRedeclaration(),
510 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000511 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000512 return true;
513 }
514
515 if (R.isForRedeclaration()) {
516 // If we're redeclaring this function anyway, forget that
517 // this was a builtin at all.
518 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
519 }
520
521 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000522 }
523 }
524 }
525
526 return false;
527}
528
Douglas Gregor4923aa22010-07-02 20:37:36 +0000529/// \brief Determine whether we can declare a special member function within
530/// the class at this point.
531static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
532 const CXXRecordDecl *Class) {
533 // We need to have a definition for the class.
534 if (!Class->getDefinition() || Class->isDependentContext())
535 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000536
Douglas Gregor4923aa22010-07-02 20:37:36 +0000537 // We can't be in the middle of defining the class.
538 if (const RecordType *RecordTy
539 = Context.getTypeDeclType(Class)->getAs<RecordType>())
540 return !RecordTy->isBeingDefined();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000541
Douglas Gregor4923aa22010-07-02 20:37:36 +0000542 return false;
543}
544
545void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000546 if (!CanDeclareSpecialMemberFunction(Context, Class))
547 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000548
549 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000550 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000551 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000552
Douglas Gregor22584312010-07-02 23:41:54 +0000553 // If the copy constructor has not yet been declared, do so now.
554 if (!Class->hasDeclaredCopyConstructor())
555 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556
Douglas Gregora376d102010-07-02 21:50:04 +0000557 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000558 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000559 DeclareImplicitCopyAssignment(Class);
560
David Blaikie4e4d0842012-03-11 07:00:24 +0000561 if (getLangOpts().CPlusPlus0x) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000562 // If the move constructor has not yet been declared, do so now.
563 if (Class->needsImplicitMoveConstructor())
564 DeclareImplicitMoveConstructor(Class); // might not actually do it
565
566 // If the move assignment operator has not yet been declared, do so now.
567 if (Class->needsImplicitMoveAssignment())
568 DeclareImplicitMoveAssignment(Class); // might not actually do it
569 }
570
Douglas Gregor4923aa22010-07-02 20:37:36 +0000571 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000572 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000573 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000574}
575
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000576/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000577/// special member function.
578static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
579 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000580 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000581 case DeclarationName::CXXDestructorName:
582 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
Douglas Gregora376d102010-07-02 21:50:04 +0000584 case DeclarationName::CXXOperatorName:
585 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586
Douglas Gregora376d102010-07-02 21:50:04 +0000587 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000588 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000589 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590
Douglas Gregora376d102010-07-02 21:50:04 +0000591 return false;
592}
593
594/// \brief If there are any implicit member functions with the given name
595/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000596static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000597 DeclarationName Name,
598 const DeclContext *DC) {
599 if (!DC)
600 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601
Douglas Gregora376d102010-07-02 21:50:04 +0000602 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000603 case DeclarationName::CXXConstructorName:
604 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000605 if (Record->getDefinition() &&
606 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000607 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000608 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000609 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000610 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000611 S.DeclareImplicitCopyConstructor(Class);
David Blaikie4e4d0842012-03-11 07:00:24 +0000612 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000613 Record->needsImplicitMoveConstructor())
614 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000615 }
Douglas Gregor22584312010-07-02 23:41:54 +0000616 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora376d102010-07-02 21:50:04 +0000618 case DeclarationName::CXXDestructorName:
619 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
620 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
621 CanDeclareSpecialMemberFunction(S.Context, Record))
622 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000623 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624
Douglas Gregora376d102010-07-02 21:50:04 +0000625 case DeclarationName::CXXOperatorName:
626 if (Name.getCXXOverloadedOperator() != OO_Equal)
627 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000628
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000629 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
630 if (Record->getDefinition() &&
631 CanDeclareSpecialMemberFunction(S.Context, Record)) {
632 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
633 if (!Record->hasDeclaredCopyAssignment())
634 S.DeclareImplicitCopyAssignment(Class);
David Blaikie4e4d0842012-03-11 07:00:24 +0000635 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000636 Record->needsImplicitMoveAssignment())
637 S.DeclareImplicitMoveAssignment(Class);
638 }
639 }
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 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000643 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000644 }
645}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000646
John McCallf36e02d2009-10-09 21:13:30 +0000647// Adds all qualifying matches for a name within a decl context to the
648// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000649static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000650 bool Found = false;
651
Douglas Gregor4923aa22010-07-02 20:37:36 +0000652 // Lazily declare C++ special member functions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000653 if (S.getLangOpts().CPlusPlus)
Douglas Gregora376d102010-07-02 21:50:04 +0000654 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000655
Douglas Gregor4923aa22010-07-02 20:37:36 +0000656 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000657 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000658 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000659 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000660 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000661 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000662 Found = true;
663 }
664 }
John McCallf36e02d2009-10-09 21:13:30 +0000665
Douglas Gregor85910982010-02-12 05:48:04 +0000666 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
667 return true;
668
Douglas Gregor48026d22010-01-11 18:40:55 +0000669 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000670 != DeclarationName::CXXConversionFunctionName ||
671 R.getLookupName().getCXXNameType()->isDependentType() ||
672 !isa<CXXRecordDecl>(DC))
673 return Found;
674
675 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000676 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000677 // name lookup. Instead, any conversion function templates visible in the
678 // context of the use are considered. [...]
679 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000680 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000681 return Found;
682
683 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000685 UEnd = Unresolved->end(); U != UEnd; ++U) {
686 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
687 if (!ConvTemplate)
688 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000690 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000691 // add the conversion function template. When we deduce template
692 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000693 // type of the new declaration with the type of the function template.
694 if (R.isForRedeclaration()) {
695 R.addDecl(ConvTemplate);
696 Found = true;
697 continue;
698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000699
Douglas Gregor48026d22010-01-11 18:40:55 +0000700 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000701 // [...] For each such operator, if argument deduction succeeds
702 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000703 // name lookup.
704 //
705 // When referencing a conversion function for any purpose other than
706 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000707 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000708 // specialization into the result set. We do this to avoid forcing all
709 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000710 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000711 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000712
713 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000714 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
715 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000716
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000717 // Compute the type of the function that we would expect the conversion
718 // function to have, if it were to match the name given.
719 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000720 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
721 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000722 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000723 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000724 QualType ExpectedType
725 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000726 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000727
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000728 // Perform template argument deduction against the type that we would
729 // expect the function to have.
730 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
731 Specialization, Info)
732 == Sema::TDK_Success) {
733 R.addDecl(Specialization);
734 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000735 }
736 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000737
John McCallf36e02d2009-10-09 21:13:30 +0000738 return Found;
739}
740
John McCalld7be78a2009-11-10 07:01:13 +0000741// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000742static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000743CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000744 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000745
746 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
747
John McCalld7be78a2009-11-10 07:01:13 +0000748 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000749 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000750
John McCalld7be78a2009-11-10 07:01:13 +0000751 // Perform direct name lookup into the namespaces nominated by the
752 // using directives whose common ancestor is this namespace.
753 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
754 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
John McCalld7be78a2009-11-10 07:01:13 +0000756 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000757 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000758 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000759
760 R.resolveKind();
761
762 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000763}
764
765static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000766 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000767 return Ctx->isFileContext();
768 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000769}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000770
Douglas Gregor711be1e2010-03-15 14:33:29 +0000771// Find the next outer declaration context from this scope. This
772// routine actually returns the semantic outer context, which may
773// differ from the lexical context (encoded directly in the Scope
774// stack) when we are parsing a member of a class template. In this
775// case, the second element of the pair will be true, to indicate that
776// name lookup should continue searching in this semantic context when
777// it leaves the current template parameter scope.
778static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
779 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
780 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000781 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000782 OuterS = OuterS->getParent()) {
783 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000784 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000785 break;
786 }
787 }
788
789 // C++ [temp.local]p8:
790 // In the definition of a member of a class template that appears
791 // outside of the namespace containing the class template
792 // definition, the name of a template-parameter hides the name of
793 // a member of this namespace.
794 //
795 // Example:
796 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000797 // namespace N {
798 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000799 //
800 // template<class T> class B {
801 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000802 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000803 // }
804 //
805 // template<class C> void N::B<C>::f(C) {
806 // C b; // C is the template parameter, not N::C
807 // }
808 //
809 // In this example, the lexical context we return is the
810 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000811 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000812 !S->getParent()->isTemplateParamScope())
813 return std::make_pair(Lexical, false);
814
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000815 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000816 // For the example, this is the scope for the template parameters of
817 // template<class C>.
818 Scope *OutermostTemplateScope = S->getParent();
819 while (OutermostTemplateScope->getParent() &&
820 OutermostTemplateScope->getParent()->isTemplateParamScope())
821 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000822
Douglas Gregor711be1e2010-03-15 14:33:29 +0000823 // Find the namespace context in which the original scope occurs. In
824 // the example, this is namespace N.
825 DeclContext *Semantic = DC;
826 while (!Semantic->isFileContext())
827 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000828
Douglas Gregor711be1e2010-03-15 14:33:29 +0000829 // Find the declaration context just outside of the template
830 // parameter scope. This is the context in which the template is
831 // being lexically declaration (a namespace context). In the
832 // example, this is the global scope.
833 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
834 Lexical->Encloses(Semantic))
835 return std::make_pair(Semantic, true);
836
837 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000838}
839
John McCalla24dc2e2009-11-17 02:14:36 +0000840bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000841 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000842
843 DeclarationName Name = R.getLookupName();
844
Douglas Gregora376d102010-07-02 21:50:04 +0000845 // If this is the name of an implicitly-declared special member function,
846 // go through the scope stack to implicitly declare
847 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
848 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
849 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
850 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
851 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000852
Douglas Gregora376d102010-07-02 21:50:04 +0000853 // Implicitly declare member functions with the name we're looking for, if in
854 // fact we are in a scope where it matters.
855
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000856 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000857 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000858 I = IdResolver.begin(Name),
859 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000860
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000861 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000862 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000863 // ...During unqualified name lookup (3.4.1), the names appear as if
864 // they were declared in the nearest enclosing namespace which contains
865 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000866 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000867 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000868 //
869 // For example:
870 // namespace A { int i; }
871 // void foo() {
872 // int i;
873 // {
874 // using namespace A;
875 // ++i; // finds local 'i', A::i appears at global scope
876 // }
877 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000878 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000879 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000880 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000881 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
882
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000883 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000884 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000885 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000886 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000887 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000888 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000889 }
890 }
John McCallf36e02d2009-10-09 21:13:30 +0000891 if (Found) {
892 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000893 if (S->isClassScope())
894 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
895 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000896 return true;
897 }
898
Douglas Gregor711be1e2010-03-15 14:33:29 +0000899 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
900 S->getParent() && !S->getParent()->isTemplateParamScope()) {
901 // We've just searched the last template parameter scope and
902 // found nothing, so look into the the contexts between the
903 // lexical and semantic declaration contexts returned by
904 // findOuterContext(). This implements the name lookup behavior
905 // of C++ [temp.local]p8.
906 Ctx = OutsideOfTemplateParamDC;
907 OutsideOfTemplateParamDC = 0;
908 }
909
910 if (Ctx) {
911 DeclContext *OuterCtx;
912 bool SearchAfterTemplateScope;
913 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
914 if (SearchAfterTemplateScope)
915 OutsideOfTemplateParamDC = OuterCtx;
916
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000917 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000918 // We do not directly look into transparent contexts, since
919 // those entities will be found in the nearest enclosing
920 // non-transparent context.
921 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000922 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000923
924 // We do not look directly into function or method contexts,
925 // since all of the local variables and parameters of the
926 // function/method are present within the Scope.
927 if (Ctx->isFunctionOrMethod()) {
928 // If we have an Objective-C instance method, look for ivars
929 // in the corresponding interface.
930 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
931 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
932 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
933 ObjCInterfaceDecl *ClassDeclared;
934 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000935 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000936 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000937 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
938 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000939 R.resolveKind();
940 return true;
941 }
942 }
943 }
944 }
945
946 continue;
947 }
948
Douglas Gregore942bbe2009-09-10 16:57:35 +0000949 // Perform qualified name lookup into this context.
950 // FIXME: In some cases, we know that every name that could be found by
951 // this qualified name lookup will also be on the identifier chain. For
952 // example, inside a class without any base classes, we never need to
953 // perform qualified lookup because all of the members are on top of the
954 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000955 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000956 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000957 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000958 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000959 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000960
John McCalld7be78a2009-11-10 07:01:13 +0000961 // Stop if we ran out of scopes.
962 // FIXME: This really, really shouldn't be happening.
963 if (!S) return false;
964
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000965 // If we are looking for members, no need to look into global/namespace scope.
966 if (R.getLookupKind() == LookupMemberName)
967 return false;
968
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000969 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000970 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000971 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000972 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
973 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000974
John McCalld7be78a2009-11-10 07:01:13 +0000975 UnqualUsingDirectiveSet UDirs;
976 UDirs.visitScopeChain(Initial, S);
977 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000978
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000979 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000980 // Unqualified name lookup in C++ requires looking into scopes
981 // that aren't strictly lexical, and therefore we walk through the
982 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000983
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000984 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000985 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000986 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000987 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000988 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000989 // We found something. Look for anything else in our scope
990 // with this same name and in an acceptable identifier
991 // namespace, so that we can construct an overload set if we
992 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000993 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000994 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000995 }
996 }
997
Douglas Gregor00b4b032010-05-14 04:53:42 +0000998 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000999 R.resolveKind();
1000 return true;
1001 }
1002
Douglas Gregor00b4b032010-05-14 04:53:42 +00001003 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1004 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1005 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1006 // We've just searched the last template parameter scope and
1007 // found nothing, so look into the the contexts between the
1008 // lexical and semantic declaration contexts returned by
1009 // findOuterContext(). This implements the name lookup behavior
1010 // of C++ [temp.local]p8.
1011 Ctx = OutsideOfTemplateParamDC;
1012 OutsideOfTemplateParamDC = 0;
1013 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001014
Douglas Gregor00b4b032010-05-14 04:53:42 +00001015 if (Ctx) {
1016 DeclContext *OuterCtx;
1017 bool SearchAfterTemplateScope;
1018 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1019 if (SearchAfterTemplateScope)
1020 OutsideOfTemplateParamDC = OuterCtx;
1021
1022 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1023 // We do not directly look into transparent contexts, since
1024 // those entities will be found in the nearest enclosing
1025 // non-transparent context.
1026 if (Ctx->isTransparentContext())
1027 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001028
Douglas Gregor00b4b032010-05-14 04:53:42 +00001029 // If we have a context, and it's not a context stashed in the
1030 // template parameter scope for an out-of-line definition, also
1031 // look into that context.
1032 if (!(Found && S && S->isTemplateParamScope())) {
1033 assert(Ctx->isFileContext() &&
1034 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035
Douglas Gregor00b4b032010-05-14 04:53:42 +00001036 // Look into context considering using-directives.
1037 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1038 Found = true;
1039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001040
Douglas Gregor00b4b032010-05-14 04:53:42 +00001041 if (Found) {
1042 R.resolveKind();
1043 return true;
1044 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045
Douglas Gregor00b4b032010-05-14 04:53:42 +00001046 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1047 return false;
1048 }
1049 }
1050
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001051 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001052 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001053 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001054
John McCallf36e02d2009-10-09 21:13:30 +00001055 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001056}
1057
Douglas Gregor55368912011-12-14 16:03:29 +00001058/// \brief Retrieve the visible declaration corresponding to D, if any.
1059///
1060/// This routine determines whether the declaration D is visible in the current
1061/// module, with the current imports. If not, it checks whether any
1062/// redeclaration of D is visible, and if so, returns that declaration.
1063///
1064/// \returns D, or a visible previous declaration of D, whichever is more recent
1065/// and visible. If no declaration of D is visible, returns null.
1066static NamedDecl *getVisibleDecl(NamedDecl *D) {
1067 if (LookupResult::isVisible(D))
1068 return D;
1069
Douglas Gregor0782ef22012-01-06 22:05:37 +00001070 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1071 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001072 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Douglas Gregor0782ef22012-01-06 22:05:37 +00001073 if (LookupResult::isVisible(ND))
1074 return ND;
1075 }
Douglas Gregor55368912011-12-14 16:03:29 +00001076 }
1077
1078 return 0;
1079}
1080
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001081/// @brief Perform unqualified name lookup starting from a given
1082/// scope.
1083///
1084/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1085/// used to find names within the current scope. For example, 'x' in
1086/// @code
1087/// int x;
1088/// int f() {
1089/// return x; // unqualified name look finds 'x' in the global scope
1090/// }
1091/// @endcode
1092///
1093/// Different lookup criteria can find different names. For example, a
1094/// particular scope can have both a struct and a function of the same
1095/// name, and each can be found by certain lookup criteria. For more
1096/// information about lookup criteria, see the documentation for the
1097/// class LookupCriteria.
1098///
1099/// @param S The scope from which unqualified name lookup will
1100/// begin. If the lookup criteria permits, name lookup may also search
1101/// in the parent scopes.
1102///
1103/// @param Name The name of the entity that we are searching for.
1104///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001105/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001106/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001107/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001108///
1109/// @returns The result of name lookup, which includes zero or more
1110/// declarations and possibly additional information used to diagnose
1111/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001112bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1113 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001114 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001115
John McCalla24dc2e2009-11-17 02:14:36 +00001116 LookupNameKind NameKind = R.getLookupKind();
1117
David Blaikie4e4d0842012-03-11 07:00:24 +00001118 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001119 // Unqualified name lookup in C/Objective-C is purely lexical, so
1120 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001121 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001122 // Find the nearest non-transparent declaration scope.
1123 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001124 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001125 static_cast<DeclContext *>(S->getEntity())
1126 ->isTransparentContext()))
1127 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001128 }
1129
John McCall1d7c5282009-12-18 10:40:03 +00001130 unsigned IDNS = R.getIdentifierNamespace();
1131
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001132 // Scan up the scope chain looking for a decl that matches this
1133 // identifier that is in the appropriate namespace. This search
1134 // should not take long, as shadowing of names is uncommon, and
1135 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001136 bool LeftStartingScope = false;
1137
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001138 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001139 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001140 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001141 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001142 if (NameKind == LookupRedeclarationWithLinkage) {
1143 // Determine whether this (or a previous) declaration is
1144 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001145 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001146 LeftStartingScope = true;
1147
1148 // If we found something outside of our starting scope that
1149 // does not have linkage, skip it.
1150 if (LeftStartingScope && !((*I)->hasLinkage()))
1151 continue;
1152 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001153 else if (NameKind == LookupObjCImplicitSelfParam &&
1154 !isa<ImplicitParamDecl>(*I))
1155 continue;
1156
Douglas Gregor10ce9322011-12-02 20:08:44 +00001157 // If this declaration is module-private and it came from an AST
1158 // file, we can't see it.
Douglas Gregor447af242012-01-05 01:11:47 +00001159 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor55368912011-12-14 16:03:29 +00001160 if (!D)
Douglas Gregor10ce9322011-12-02 20:08:44 +00001161 continue;
Douglas Gregor55368912011-12-14 16:03:29 +00001162
1163 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001164
Douglas Gregor7a537402012-01-03 23:26:26 +00001165 // Check whether there are any other declarations with the same name
1166 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001167 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001168 // Find the scope in which this declaration was declared (if it
1169 // actually exists in a Scope).
1170 while (S && !S->isDeclScope(D))
1171 S = S->getParent();
1172
1173 // If the scope containing the declaration is the translation unit,
1174 // then we'll need to perform our checks based on the matching
1175 // DeclContexts rather than matching scopes.
1176 if (S && isNamespaceOrTranslationUnitScope(S))
1177 S = 0;
1178
1179 // Compute the DeclContext, if we need it.
1180 DeclContext *DC = 0;
1181 if (!S)
1182 DC = (*I)->getDeclContext()->getRedeclContext();
1183
Douglas Gregorda795b42012-01-04 16:44:10 +00001184 IdentifierResolver::iterator LastI = I;
1185 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001186 if (S) {
1187 // Match based on scope.
1188 if (!S->isDeclScope(*LastI))
1189 break;
1190 } else {
1191 // Match based on DeclContext.
1192 DeclContext *LastDC
1193 = (*LastI)->getDeclContext()->getRedeclContext();
1194 if (!LastDC->Equals(DC))
1195 break;
1196 }
1197
1198 // If the declaration isn't in the right namespace, skip it.
Douglas Gregorda795b42012-01-04 16:44:10 +00001199 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1200 continue;
Douglas Gregor117c4562012-01-13 23:06:53 +00001201
Douglas Gregor447af242012-01-05 01:11:47 +00001202 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregorda795b42012-01-04 16:44:10 +00001203 if (D)
1204 R.addDecl(D);
1205 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001206
Douglas Gregorda795b42012-01-04 16:44:10 +00001207 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001208 }
John McCallf36e02d2009-10-09 21:13:30 +00001209 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001210 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001211 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001212 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001213 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001214 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001215 }
1216
1217 // If we didn't find a use of this identifier, and if the identifier
1218 // corresponds to a compiler builtin, create the decl object for the builtin
1219 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001220 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1221 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001222
Axel Naumannf8291a12011-02-24 16:47:47 +00001223 // If we didn't find a use of this identifier, the ExternalSource
1224 // may be able to handle the situation.
1225 // Note: some lookup failures are expected!
1226 // See e.g. R.isForRedeclaration().
1227 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001228}
1229
John McCall6e247262009-10-10 05:48:19 +00001230/// @brief Perform qualified name lookup in the namespaces nominated by
1231/// using directives by the given context.
1232///
1233/// C++98 [namespace.qual]p2:
1234/// Given X::m (where X is a user-declared namespace), or given ::m
1235/// (where X is the global namespace), let S be the set of all
1236/// declarations of m in X and in the transitive closure of all
1237/// namespaces nominated by using-directives in X and its used
1238/// namespaces, except that using-directives are ignored in any
1239/// namespace, including X, directly containing one or more
1240/// declarations of m. No namespace is searched more than once in
1241/// the lookup of a name. If S is the empty set, the program is
1242/// ill-formed. Otherwise, if S has exactly one member, or if the
1243/// context of the reference is a using-declaration
1244/// (namespace.udecl), S is the required set of declarations of
1245/// m. Otherwise if the use of m is not one that allows a unique
1246/// declaration to be chosen from S, the program is ill-formed.
1247/// C++98 [namespace.qual]p5:
1248/// During the lookup of a qualified namespace member name, if the
1249/// lookup finds more than one declaration of the member, and if one
1250/// declaration introduces a class name or enumeration name and the
1251/// other declarations either introduce the same object, the same
1252/// enumerator or a set of functions, the non-type name hides the
1253/// class or enumeration name if and only if the declarations are
1254/// from the same namespace; otherwise (the declarations are from
1255/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001256static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001257 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001258 assert(StartDC->isFileContext() && "start context is not a file context");
1259
1260 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1261 DeclContext::udir_iterator E = StartDC->using_directives_end();
1262
1263 if (I == E) return false;
1264
1265 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001266 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001267 Visited.insert(StartDC);
1268
1269 // We have not yet looked into these namespaces, much less added
1270 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001271 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001272
1273 // We have already looked into the initial namespace; seed the queue
1274 // with its using-children.
1275 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001276 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001277 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001278 Queue.push_back(ND);
1279 }
1280
1281 // The easiest way to implement the restriction in [namespace.qual]p5
1282 // is to check whether any of the individual results found a tag
1283 // and, if so, to declare an ambiguity if the final result is not
1284 // a tag.
1285 bool FoundTag = false;
1286 bool FoundNonTag = false;
1287
John McCall7d384dd2009-11-18 07:57:50 +00001288 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001289
1290 bool Found = false;
1291 while (!Queue.empty()) {
1292 NamespaceDecl *ND = Queue.back();
1293 Queue.pop_back();
1294
1295 // We go through some convolutions here to avoid copying results
1296 // between LookupResults.
1297 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001298 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001299 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001300
1301 if (FoundDirect) {
1302 // First do any local hiding.
1303 DirectR.resolveKind();
1304
1305 // If the local result is a tag, remember that.
1306 if (DirectR.isSingleTagDecl())
1307 FoundTag = true;
1308 else
1309 FoundNonTag = true;
1310
1311 // Append the local results to the total results if necessary.
1312 if (UseLocal) {
1313 R.addAllDecls(LocalR);
1314 LocalR.clear();
1315 }
1316 }
1317
1318 // If we find names in this namespace, ignore its using directives.
1319 if (FoundDirect) {
1320 Found = true;
1321 continue;
1322 }
1323
1324 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1325 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001326 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001327 Queue.push_back(Nom);
1328 }
1329 }
1330
1331 if (Found) {
1332 if (FoundTag && FoundNonTag)
1333 R.setAmbiguousQualifiedTagHiding();
1334 else
1335 R.resolveKind();
1336 }
1337
1338 return Found;
1339}
1340
Douglas Gregor8071e422010-08-15 06:18:01 +00001341/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001342static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001343 CXXBasePath &Path,
1344 void *Name) {
1345 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001346
Douglas Gregor8071e422010-08-15 06:18:01 +00001347 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1348 Path.Decls = BaseRecord->lookup(N);
1349 return Path.Decls.first != Path.Decls.second;
1350}
1351
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001352/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001353/// static members, nested types, and enumerators.
1354template<typename InputIterator>
1355static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1356 Decl *D = (*First)->getUnderlyingDecl();
1357 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1358 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001360 if (isa<CXXMethodDecl>(D)) {
1361 // Determine whether all of the methods are static.
1362 bool AllMethodsAreStatic = true;
1363 for(; First != Last; ++First) {
1364 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001365
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001366 if (!isa<CXXMethodDecl>(D)) {
1367 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1368 break;
1369 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001370
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001371 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1372 AllMethodsAreStatic = false;
1373 break;
1374 }
1375 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001376
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001377 if (AllMethodsAreStatic)
1378 return true;
1379 }
1380
1381 return false;
1382}
1383
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001384/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001385///
1386/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1387/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001388/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001389///
1390/// Different lookup criteria can find different names. For example, a
1391/// particular scope can have both a struct and a function of the same
1392/// name, and each can be found by certain lookup criteria. For more
1393/// information about lookup criteria, see the documentation for the
1394/// class LookupCriteria.
1395///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001396/// \param R captures both the lookup criteria and any lookup results found.
1397///
1398/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001399/// search. If the lookup criteria permits, name lookup may also search
1400/// in the parent contexts or (for C++ classes) base classes.
1401///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001403/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001404///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001405/// \returns true if lookup succeeded, false if it failed.
1406bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1407 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001408 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001409
John McCalla24dc2e2009-11-17 02:14:36 +00001410 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001411 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001413 // Make sure that the declaration context is complete.
1414 assert((!isa<TagDecl>(LookupCtx) ||
1415 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001416 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001417 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001418 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001420 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001421 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001422 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001423 if (isa<CXXRecordDecl>(LookupCtx))
1424 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001425 return true;
1426 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001427
John McCall6e247262009-10-10 05:48:19 +00001428 // Don't descend into implied contexts for redeclarations.
1429 // C++98 [namespace.qual]p6:
1430 // In a declaration for a namespace member in which the
1431 // declarator-id is a qualified-id, given that the qualified-id
1432 // for the namespace member has the form
1433 // nested-name-specifier unqualified-id
1434 // the unqualified-id shall name a member of the namespace
1435 // designated by the nested-name-specifier.
1436 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001437 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001438 return false;
1439
John McCalla24dc2e2009-11-17 02:14:36 +00001440 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001441 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001442 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001443
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001444 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001445 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001446 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001447 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001448 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001449
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001450 // If we're performing qualified name lookup into a dependent class,
1451 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001452 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001453 // template instantiation time (at which point all bases will be available)
1454 // or we have to fail.
1455 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1456 LookupRec->hasAnyDependentBases()) {
1457 R.setNotFoundInCurrentInstantiation();
1458 return false;
1459 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001460
Douglas Gregor7176fff2009-01-15 00:26:24 +00001461 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001462 CXXBasePaths Paths;
1463 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001464
1465 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001466 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001467 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001468 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001469 case LookupOrdinaryName:
1470 case LookupMemberName:
1471 case LookupRedeclarationWithLinkage:
1472 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1473 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001474
Douglas Gregora8f32e02009-10-06 17:59:45 +00001475 case LookupTagName:
1476 BaseCallback = &CXXRecordDecl::FindTagMember;
1477 break;
John McCall9f54ad42009-12-10 09:41:52 +00001478
Douglas Gregor8071e422010-08-15 06:18:01 +00001479 case LookupAnyName:
1480 BaseCallback = &LookupAnyMember;
1481 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001482
John McCall9f54ad42009-12-10 09:41:52 +00001483 case LookupUsingDeclName:
1484 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001485
Douglas Gregora8f32e02009-10-06 17:59:45 +00001486 case LookupOperatorName:
1487 case LookupNamespaceName:
1488 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001489 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001490 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001491 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001492
Douglas Gregora8f32e02009-10-06 17:59:45 +00001493 case LookupNestedNameSpecifierName:
1494 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1495 break;
1496 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001497
John McCalla24dc2e2009-11-17 02:14:36 +00001498 if (!LookupRec->lookupInBases(BaseCallback,
1499 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001500 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001501
John McCall92f88312010-01-23 00:46:32 +00001502 R.setNamingClass(LookupRec);
1503
Douglas Gregor7176fff2009-01-15 00:26:24 +00001504 // C++ [class.member.lookup]p2:
1505 // [...] If the resulting set of declarations are not all from
1506 // sub-objects of the same type, or the set has a nonstatic member
1507 // and includes members from distinct sub-objects, there is an
1508 // ambiguity and the program is ill-formed. Otherwise that set is
1509 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001510 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001511 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001512 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001513
Douglas Gregora8f32e02009-10-06 17:59:45 +00001514 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001515 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001516 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001517
John McCall46460a62010-01-20 21:53:11 +00001518 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1519 // across all paths.
1520 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001521
Douglas Gregor7176fff2009-01-15 00:26:24 +00001522 // Determine whether we're looking at a distinct sub-object or not.
1523 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001524 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001525 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1526 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001527 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001528 }
1529
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001530 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001531 != Context.getCanonicalType(PathElement.Base->getType())) {
1532 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001533 // different types. If the declaration sets aren't the same, this
1534 // this lookup is ambiguous.
1535 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1536 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1537 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1538 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001539
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001540 while (FirstD != FirstPath->Decls.second &&
1541 CurrentD != Path->Decls.second) {
1542 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1543 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1544 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001545
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001546 ++FirstD;
1547 ++CurrentD;
1548 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001549
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001550 if (FirstD == FirstPath->Decls.second &&
1551 CurrentD == Path->Decls.second)
1552 continue;
1553 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001554
John McCallf36e02d2009-10-09 21:13:30 +00001555 R.setAmbiguousBaseSubobjectTypes(Paths);
1556 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001557 }
1558
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001559 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001560 // We have a different subobject of the same type.
1561
1562 // C++ [class.member.lookup]p5:
1563 // A static member, a nested type or an enumerator defined in
1564 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001565 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001566 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001567 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001568
Douglas Gregor7176fff2009-01-15 00:26:24 +00001569 // We have found a nonstatic member name in multiple, distinct
1570 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001571 R.setAmbiguousBaseSubobjects(Paths);
1572 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001573 }
1574 }
1575
1576 // Lookup in a base class succeeded; return these results.
1577
John McCallf36e02d2009-10-09 21:13:30 +00001578 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001579 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1580 NamedDecl *D = *I;
1581 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1582 D->getAccess());
1583 R.addDecl(D, AS);
1584 }
John McCallf36e02d2009-10-09 21:13:30 +00001585 R.resolveKind();
1586 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001587}
1588
1589/// @brief Performs name lookup for a name that was parsed in the
1590/// source code, and may contain a C++ scope specifier.
1591///
1592/// This routine is a convenience routine meant to be called from
1593/// contexts that receive a name and an optional C++ scope specifier
1594/// (e.g., "N::M::x"). It will then perform either qualified or
1595/// unqualified name lookup (with LookupQualifiedName or LookupName,
1596/// respectively) on the given name and return those results.
1597///
1598/// @param S The scope from which unqualified name lookup will
1599/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001600///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001601/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001602///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001603/// @param EnteringContext Indicates whether we are going to enter the
1604/// context of the scope-specifier SS (if present).
1605///
John McCallf36e02d2009-10-09 21:13:30 +00001606/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001607bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001608 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001609 if (SS && SS->isInvalid()) {
1610 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001611 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001612 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001613 }
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Douglas Gregor495c35d2009-08-25 22:51:20 +00001615 if (SS && SS->isSet()) {
1616 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001617 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001618 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001619 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001620 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
John McCalla24dc2e2009-11-17 02:14:36 +00001622 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001623 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001624 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001625
Douglas Gregor495c35d2009-08-25 22:51:20 +00001626 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001627 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001628 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001629 R.setNotFoundInCurrentInstantiation();
1630 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001631 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001632 }
1633
Mike Stump1eb44332009-09-09 15:08:12 +00001634 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001635 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001636}
1637
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001638
Douglas Gregor7176fff2009-01-15 00:26:24 +00001639/// @brief Produce a diagnostic describing the ambiguity that resulted
1640/// from name lookup.
1641///
1642/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001643///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001644/// @param Name The name of the entity that name lookup was
1645/// searching for.
1646///
1647/// @param NameLoc The location of the name within the source code.
1648///
1649/// @param LookupRange A source range that provides more
1650/// source-location information concerning the lookup itself. For
1651/// example, this range might highlight a nested-name-specifier that
1652/// precedes the name.
1653///
1654/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001655bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001656 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1657
John McCalla24dc2e2009-11-17 02:14:36 +00001658 DeclarationName Name = Result.getLookupName();
1659 SourceLocation NameLoc = Result.getNameLoc();
1660 SourceRange LookupRange = Result.getContextRange();
1661
John McCall6e247262009-10-10 05:48:19 +00001662 switch (Result.getAmbiguityKind()) {
1663 case LookupResult::AmbiguousBaseSubobjects: {
1664 CXXBasePaths *Paths = Result.getBasePaths();
1665 QualType SubobjectType = Paths->front().back().Base->getType();
1666 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1667 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1668 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001669
John McCall6e247262009-10-10 05:48:19 +00001670 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1671 while (isa<CXXMethodDecl>(*Found) &&
1672 cast<CXXMethodDecl>(*Found)->isStatic())
1673 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001674
John McCall6e247262009-10-10 05:48:19 +00001675 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001676
John McCall6e247262009-10-10 05:48:19 +00001677 return true;
1678 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001679
John McCall6e247262009-10-10 05:48:19 +00001680 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001681 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1682 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001683
John McCall6e247262009-10-10 05:48:19 +00001684 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001685 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001686 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1687 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001688 Path != PathEnd; ++Path) {
1689 Decl *D = *Path->Decls.first;
1690 if (DeclsPrinted.insert(D).second)
1691 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1692 }
1693
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001694 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001695 }
1696
John McCall6e247262009-10-10 05:48:19 +00001697 case LookupResult::AmbiguousTagHiding: {
1698 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001699
John McCall6e247262009-10-10 05:48:19 +00001700 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1701
1702 LookupResult::iterator DI, DE = Result.end();
1703 for (DI = Result.begin(); DI != DE; ++DI)
1704 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1705 TagDecls.insert(TD);
1706 Diag(TD->getLocation(), diag::note_hidden_tag);
1707 }
1708
1709 for (DI = Result.begin(); DI != DE; ++DI)
1710 if (!isa<TagDecl>(*DI))
1711 Diag((*DI)->getLocation(), diag::note_hiding_object);
1712
1713 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001714 LookupResult::Filter F = Result.makeFilter();
1715 while (F.hasNext()) {
1716 if (TagDecls.count(F.next()))
1717 F.erase();
1718 }
1719 F.done();
John McCall6e247262009-10-10 05:48:19 +00001720
1721 return true;
1722 }
1723
1724 case LookupResult::AmbiguousReference: {
1725 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001726
John McCall6e247262009-10-10 05:48:19 +00001727 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1728 for (; DI != DE; ++DI)
1729 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001730
John McCall6e247262009-10-10 05:48:19 +00001731 return true;
1732 }
1733 }
1734
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001735 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001736}
Douglas Gregorfa047642009-02-04 00:32:51 +00001737
John McCallc7e04da2010-05-28 18:45:08 +00001738namespace {
1739 struct AssociatedLookup {
1740 AssociatedLookup(Sema &S,
1741 Sema::AssociatedNamespaceSet &Namespaces,
1742 Sema::AssociatedClassSet &Classes)
1743 : S(S), Namespaces(Namespaces), Classes(Classes) {
1744 }
1745
1746 Sema &S;
1747 Sema::AssociatedNamespaceSet &Namespaces;
1748 Sema::AssociatedClassSet &Classes;
1749 };
1750}
1751
Mike Stump1eb44332009-09-09 15:08:12 +00001752static void
John McCallc7e04da2010-05-28 18:45:08 +00001753addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001754
Douglas Gregor54022952010-04-30 07:08:38 +00001755static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1756 DeclContext *Ctx) {
1757 // Add the associated namespace for this class.
1758
1759 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1760 // be a locally scoped record.
1761
Sebastian Redl410c4f22010-08-31 20:53:31 +00001762 // We skip out of inline namespaces. The innermost non-inline namespace
1763 // contains all names of all its nested inline namespaces anyway, so we can
1764 // replace the entire inline namespace tree with its root.
1765 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1766 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001767 Ctx = Ctx->getParent();
1768
John McCall6ff07852009-08-07 22:18:02 +00001769 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001770 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001771}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001772
Mike Stump1eb44332009-09-09 15:08:12 +00001773// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001774// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001775static void
John McCallc7e04da2010-05-28 18:45:08 +00001776addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1777 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001778 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001779 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001780 switch (Arg.getKind()) {
1781 case TemplateArgument::Null:
1782 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Douglas Gregor69be8d62009-07-08 07:51:57 +00001784 case TemplateArgument::Type:
1785 // [...] the namespaces and classes associated with the types of the
1786 // template arguments provided for template type parameters (excluding
1787 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001788 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001789 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001790
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001791 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001792 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001793 // [...] the namespaces in which any template template arguments are
1794 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001795 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001796 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001797 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001798 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001799 DeclContext *Ctx = ClassTemplate->getDeclContext();
1800 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001801 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001802 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001803 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001804 }
1805 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001806 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001807
Douglas Gregor788cd062009-11-11 01:00:40 +00001808 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001809 case TemplateArgument::Integral:
1810 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001811 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001812 // associated namespaces. ]
1813 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Douglas Gregor69be8d62009-07-08 07:51:57 +00001815 case TemplateArgument::Pack:
1816 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1817 PEnd = Arg.pack_end();
1818 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001819 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001820 break;
1821 }
1822}
1823
Douglas Gregorfa047642009-02-04 00:32:51 +00001824// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001825// argument-dependent lookup with an argument of class type
1826// (C++ [basic.lookup.koenig]p2).
1827static void
John McCallc7e04da2010-05-28 18:45:08 +00001828addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1829 CXXRecordDecl *Class) {
1830
1831 // Just silently ignore anything whose name is __va_list_tag.
1832 if (Class->getDeclName() == Result.S.VAListTagName)
1833 return;
1834
Douglas Gregorfa047642009-02-04 00:32:51 +00001835 // C++ [basic.lookup.koenig]p2:
1836 // [...]
1837 // -- If T is a class type (including unions), its associated
1838 // classes are: the class itself; the class of which it is a
1839 // member, if any; and its direct and indirect base
1840 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001841 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001842
1843 // Add the class of which it is a member, if any.
1844 DeclContext *Ctx = Class->getDeclContext();
1845 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001846 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001847 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001848 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Douglas Gregorfa047642009-02-04 00:32:51 +00001850 // Add the class itself. If we've already seen this class, we don't
1851 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001852 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001853 return;
1854
Mike Stump1eb44332009-09-09 15:08:12 +00001855 // -- If T is a template-id, its associated namespaces and classes are
1856 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001857 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001858 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001859 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001860 // namespaces in which any template template arguments are defined; and
1861 // the classes in which any member templates used as template template
1862 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001863 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001864 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001865 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1866 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1867 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001868 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001869 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001870 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Douglas Gregor69be8d62009-07-08 07:51:57 +00001872 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1873 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001874 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
John McCall86ff3082010-02-04 22:26:26 +00001877 // Only recurse into base classes for complete types.
1878 if (!Class->hasDefinition()) {
1879 // FIXME: we might need to instantiate templates here
1880 return;
1881 }
1882
Douglas Gregorfa047642009-02-04 00:32:51 +00001883 // Add direct and indirect base classes along with their associated
1884 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001885 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001886 Bases.push_back(Class);
1887 while (!Bases.empty()) {
1888 // Pop this class off the stack.
1889 Class = Bases.back();
1890 Bases.pop_back();
1891
1892 // Visit the base classes.
1893 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1894 BaseEnd = Class->bases_end();
1895 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001896 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001897 // In dependent contexts, we do ADL twice, and the first time around,
1898 // the base type might be a dependent TemplateSpecializationType, or a
1899 // TemplateTypeParmType. If that happens, simply ignore it.
1900 // FIXME: If we want to support export, we probably need to add the
1901 // namespace of the template in a TemplateSpecializationType, or even
1902 // the classes and namespaces of known non-dependent arguments.
1903 if (!BaseType)
1904 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001905 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001906 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001907 // Find the associated namespace for this base class.
1908 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001909 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001910
1911 // Make sure we visit the bases of this base class.
1912 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1913 Bases.push_back(BaseDecl);
1914 }
1915 }
1916 }
1917}
1918
1919// \brief Add the associated classes and namespaces for
1920// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001921// (C++ [basic.lookup.koenig]p2).
1922static void
John McCallc7e04da2010-05-28 18:45:08 +00001923addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001924 // C++ [basic.lookup.koenig]p2:
1925 //
1926 // For each argument type T in the function call, there is a set
1927 // of zero or more associated namespaces and a set of zero or more
1928 // associated classes to be considered. The sets of namespaces and
1929 // classes is determined entirely by the types of the function
1930 // arguments (and the namespace of any template template
1931 // argument). Typedef names and using-declarations used to specify
1932 // the types do not contribute to this set. The sets of namespaces
1933 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001934
Chris Lattner5f9e2722011-07-23 10:55:15 +00001935 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001936 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1937
Douglas Gregorfa047642009-02-04 00:32:51 +00001938 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001939 switch (T->getTypeClass()) {
1940
1941#define TYPE(Class, Base)
1942#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1943#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1944#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1945#define ABSTRACT_TYPE(Class, Base)
1946#include "clang/AST/TypeNodes.def"
1947 // T is canonical. We can also ignore dependent types because
1948 // we don't need to do ADL at the definition point, but if we
1949 // wanted to implement template export (or if we find some other
1950 // use for associated classes and namespaces...) this would be
1951 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001952 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001953
John McCallfa4edcf2010-05-28 06:08:54 +00001954 // -- If T is a pointer to U or an array of U, its associated
1955 // namespaces and classes are those associated with U.
1956 case Type::Pointer:
1957 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1958 continue;
1959 case Type::ConstantArray:
1960 case Type::IncompleteArray:
1961 case Type::VariableArray:
1962 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1963 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001964
John McCallfa4edcf2010-05-28 06:08:54 +00001965 // -- If T is a fundamental type, its associated sets of
1966 // namespaces and classes are both empty.
1967 case Type::Builtin:
1968 break;
1969
1970 // -- If T is a class type (including unions), its associated
1971 // classes are: the class itself; the class of which it is a
1972 // member, if any; and its direct and indirect base
1973 // classes. Its associated namespaces are the namespaces in
1974 // which its associated classes are defined.
1975 case Type::Record: {
1976 CXXRecordDecl *Class
1977 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001978 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001979 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001980 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001981
John McCallfa4edcf2010-05-28 06:08:54 +00001982 // -- If T is an enumeration type, its associated namespace is
1983 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001984 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001985 // it has no associated class.
1986 case Type::Enum: {
1987 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001988
John McCallfa4edcf2010-05-28 06:08:54 +00001989 DeclContext *Ctx = Enum->getDeclContext();
1990 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001991 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001992
John McCallfa4edcf2010-05-28 06:08:54 +00001993 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001994 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001995
John McCallfa4edcf2010-05-28 06:08:54 +00001996 break;
1997 }
1998
1999 // -- If T is a function type, its associated namespaces and
2000 // classes are those associated with the function parameter
2001 // types and those associated with the return type.
2002 case Type::FunctionProto: {
2003 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2004 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2005 ArgEnd = Proto->arg_type_end();
2006 Arg != ArgEnd; ++Arg)
2007 Queue.push_back(Arg->getTypePtr());
2008 // fallthrough
2009 }
2010 case Type::FunctionNoProto: {
2011 const FunctionType *FnType = cast<FunctionType>(T);
2012 T = FnType->getResultType().getTypePtr();
2013 continue;
2014 }
2015
2016 // -- If T is a pointer to a member function of a class X, its
2017 // associated namespaces and classes are those associated
2018 // with the function parameter types and return type,
2019 // together with those associated with X.
2020 //
2021 // -- If T is a pointer to a data member of class X, its
2022 // associated namespaces and classes are those associated
2023 // with the member type together with those associated with
2024 // X.
2025 case Type::MemberPointer: {
2026 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2027
2028 // Queue up the class type into which this points.
2029 Queue.push_back(MemberPtr->getClass());
2030
2031 // And directly continue with the pointee type.
2032 T = MemberPtr->getPointeeType().getTypePtr();
2033 continue;
2034 }
2035
2036 // As an extension, treat this like a normal pointer.
2037 case Type::BlockPointer:
2038 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2039 continue;
2040
2041 // References aren't covered by the standard, but that's such an
2042 // obvious defect that we cover them anyway.
2043 case Type::LValueReference:
2044 case Type::RValueReference:
2045 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2046 continue;
2047
2048 // These are fundamental types.
2049 case Type::Vector:
2050 case Type::ExtVector:
2051 case Type::Complex:
2052 break;
2053
Douglas Gregorf25760e2011-04-12 01:02:45 +00002054 // If T is an Objective-C object or interface type, or a pointer to an
2055 // object or interface type, the associated namespace is the global
2056 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002057 case Type::ObjCObject:
2058 case Type::ObjCInterface:
2059 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002060 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002061 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002062
2063 // Atomic types are just wrappers; use the associations of the
2064 // contained type.
2065 case Type::Atomic:
2066 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2067 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002068 }
2069
2070 if (Queue.empty()) break;
2071 T = Queue.back();
2072 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002073 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002074}
2075
2076/// \brief Find the associated classes and namespaces for
2077/// argument-dependent lookup for a call with the given set of
2078/// arguments.
2079///
2080/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002081/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002082/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002083void
Ahmed Charles13a140c2012-02-25 11:00:22 +00002084Sema::FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002085 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002086 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002087 AssociatedNamespaces.clear();
2088 AssociatedClasses.clear();
2089
John McCallc7e04da2010-05-28 18:45:08 +00002090 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2091
Douglas Gregorfa047642009-02-04 00:32:51 +00002092 // C++ [basic.lookup.koenig]p2:
2093 // For each argument type T in the function call, there is a set
2094 // of zero or more associated namespaces and a set of zero or more
2095 // associated classes to be considered. The sets of namespaces and
2096 // classes is determined entirely by the types of the function
2097 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002098 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002099 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002100 Expr *Arg = Args[ArgIdx];
2101
2102 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002103 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002104 continue;
2105 }
2106
2107 // [...] In addition, if the argument is the name or address of a
2108 // set of overloaded functions and/or function templates, its
2109 // associated classes and namespaces are the union of those
2110 // associated with each of the members of the set: the namespace
2111 // in which the function or function template is defined and the
2112 // classes and namespaces associated with its (non-dependent)
2113 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002114 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002115 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002116 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002117 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002118
John McCallc7e04da2010-05-28 18:45:08 +00002119 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2120 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002121
John McCallc7e04da2010-05-28 18:45:08 +00002122 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2123 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002124 // Look through any using declarations to find the underlying function.
2125 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002126
Chandler Carruthbd647292009-12-29 06:17:27 +00002127 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2128 if (!FDecl)
2129 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002130
2131 // Add the classes and namespaces associated with the parameter
2132 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002133 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002134 }
2135 }
2136}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002137
2138/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2139/// an acceptable non-member overloaded operator for a call whose
2140/// arguments have types T1 (and, if non-empty, T2). This routine
2141/// implements the check in C++ [over.match.oper]p3b2 concerning
2142/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002143static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002144IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2145 QualType T1, QualType T2,
2146 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002147 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2148 return true;
2149
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002150 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2151 return true;
2152
John McCall183700f2009-09-21 23:43:11 +00002153 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002154 if (Proto->getNumArgs() < 1)
2155 return false;
2156
2157 if (T1->isEnumeralType()) {
2158 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002159 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002160 return true;
2161 }
2162
2163 if (Proto->getNumArgs() < 2)
2164 return false;
2165
2166 if (!T2.isNull() && T2->isEnumeralType()) {
2167 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002168 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002169 return true;
2170 }
2171
2172 return false;
2173}
2174
John McCall7d384dd2009-11-18 07:57:50 +00002175NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002176 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002177 LookupNameKind NameKind,
2178 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002179 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002180 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002181 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002182}
2183
Douglas Gregor6e378de2009-04-23 23:18:26 +00002184/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002185ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002186 SourceLocation IdLoc,
2187 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002188 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002189 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002190 return cast_or_null<ObjCProtocolDecl>(D);
2191}
2192
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002193void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002194 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002195 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002196 // C++ [over.match.oper]p3:
2197 // -- The set of non-member candidates is the result of the
2198 // unqualified lookup of operator@ in the context of the
2199 // expression according to the usual rules for name lookup in
2200 // unqualified function calls (3.4.2) except that all member
2201 // functions are ignored. However, if no operand has a class
2202 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002203 // that have a first parameter of type T1 or "reference to
2204 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002205 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002206 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002207 // when T2 is an enumeration type, are candidate functions.
2208 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002209 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2210 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002212 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2213
John McCallf36e02d2009-10-09 21:13:30 +00002214 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002215 return;
2216
2217 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2218 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002219 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2220 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002221 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002222 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002223 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002224 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002225 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002226 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002227 // later?
2228 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002229 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002230 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002231 }
2232}
2233
Sean Huntc39b6bc2011-06-24 02:11:39 +00002234Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002235 CXXSpecialMember SM,
2236 bool ConstArg,
2237 bool VolatileArg,
2238 bool RValueThis,
2239 bool ConstThis,
2240 bool VolatileThis) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002241 RD = RD->getDefinition();
2242 assert((RD && !RD->isBeingDefined()) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002243 "doing special member lookup into record that isn't fully complete");
2244 if (RValueThis || ConstThis || VolatileThis)
2245 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2246 "constructors and destructors always have unqualified lvalue this");
2247 if (ConstArg || VolatileArg)
2248 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2249 "parameter-less special members can't have qualified arguments");
2250
2251 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002252 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002253 ID.AddInteger(SM);
2254 ID.AddInteger(ConstArg);
2255 ID.AddInteger(VolatileArg);
2256 ID.AddInteger(RValueThis);
2257 ID.AddInteger(ConstThis);
2258 ID.AddInteger(VolatileThis);
2259
2260 void *InsertPoint;
2261 SpecialMemberOverloadResult *Result =
2262 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2263
2264 // This was already cached
2265 if (Result)
2266 return Result;
2267
Sean Hunt30543582011-06-07 00:11:58 +00002268 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2269 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002270 SpecialMemberCache.InsertNode(Result, InsertPoint);
2271
2272 if (SM == CXXDestructor) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002273 if (!RD->hasDeclaredDestructor())
2274 DeclareImplicitDestructor(RD);
2275 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002276 assert(DD && "record without a destructor");
2277 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002278 Result->setKind(DD->isDeleted() ?
2279 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002280 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002281 return Result;
2282 }
2283
Sean Huntb320e0c2011-06-10 03:50:41 +00002284 // Prepare for overload resolution. Here we construct a synthetic argument
2285 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002286 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002287 DeclarationName Name;
2288 Expr *Arg = 0;
2289 unsigned NumArgs;
2290
Richard Smith704c8f72012-04-20 18:46:14 +00002291 QualType ArgType = CanTy;
2292 ExprValueKind VK = VK_LValue;
2293
Sean Huntb320e0c2011-06-10 03:50:41 +00002294 if (SM == CXXDefaultConstructor) {
2295 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2296 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002297 if (RD->needsImplicitDefaultConstructor())
2298 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002299 } else {
2300 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2301 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002302 if (!RD->hasDeclaredCopyConstructor())
2303 DeclareImplicitCopyConstructor(RD);
David Blaikie4e4d0842012-03-11 07:00:24 +00002304 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002305 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002306 } else {
2307 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002308 if (!RD->hasDeclaredCopyAssignment())
2309 DeclareImplicitCopyAssignment(RD);
David Blaikie4e4d0842012-03-11 07:00:24 +00002310 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002311 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002312 }
2313
Sean Huntb320e0c2011-06-10 03:50:41 +00002314 if (ConstArg)
2315 ArgType.addConst();
2316 if (VolatileArg)
2317 ArgType.addVolatile();
2318
2319 // This isn't /really/ specified by the standard, but it's implied
2320 // we should be working from an RValue in the case of move to ensure
2321 // that we prefer to bind to rvalue references, and an LValue in the
2322 // case of copy to ensure we don't bind to rvalue references.
2323 // Possibly an XValue is actually correct in the case of move, but
2324 // there is no semantic difference for class types in this restricted
2325 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002326 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002327 VK = VK_LValue;
2328 else
2329 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002330 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002331
Richard Smith704c8f72012-04-20 18:46:14 +00002332 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2333
2334 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002335 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002336 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002337 }
2338
2339 // Create the object argument
2340 QualType ThisTy = CanTy;
2341 if (ConstThis)
2342 ThisTy.addConst();
2343 if (VolatileThis)
2344 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002345 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002346 OpaqueValueExpr(SourceLocation(), ThisTy,
2347 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002348
2349 // Now we perform lookup on the name we computed earlier and do overload
2350 // resolution. Lookup is only performed directly into the class since there
2351 // will always be a (possibly implicit) declaration to shadow any others.
2352 OverloadCandidateSet OCS((SourceLocation()));
2353 DeclContext::lookup_iterator I, E;
Sean Huntb320e0c2011-06-10 03:50:41 +00002354
Sean Huntc39b6bc2011-06-24 02:11:39 +00002355 llvm::tie(I, E) = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002356 assert((I != E) &&
2357 "lookup for a constructor or assignment operator was empty");
2358 for ( ; I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002359 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002360
Sean Huntc39b6bc2011-06-24 02:11:39 +00002361 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002362 continue;
2363
Sean Huntc39b6bc2011-06-24 02:11:39 +00002364 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2365 // FIXME: [namespace.udecl]p15 says that we should only consider a
2366 // using declaration here if it does not match a declaration in the
2367 // derived class. We do not implement this correctly in other cases
2368 // either.
2369 Cand = U->getTargetDecl();
2370
2371 if (Cand->isInvalidDecl())
2372 continue;
2373 }
2374
2375 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002376 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002377 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002378 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2379 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002380 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002381 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2382 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002383 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002384 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002385 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2386 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002387 RD, 0, ThisTy, Classification,
2388 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002389 OCS, true);
2390 else
2391 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002392 0, llvm::makeArrayRef(&Arg, NumArgs),
2393 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002394 } else {
2395 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002396 }
2397 }
2398
2399 OverloadCandidateSet::iterator Best;
2400 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2401 case OR_Success:
2402 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002403 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002404 break;
2405
2406 case OR_Deleted:
2407 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002408 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002409 break;
2410
2411 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002412 Result->setMethod(0);
2413 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2414 break;
2415
Sean Huntb320e0c2011-06-10 03:50:41 +00002416 case OR_No_Viable_Function:
2417 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002418 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002419 break;
2420 }
2421
2422 return Result;
2423}
2424
2425/// \brief Look up the default constructor for the given class.
2426CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002427 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002428 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2429 false, false);
2430
2431 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002432}
2433
Sean Hunt661c67a2011-06-21 23:42:56 +00002434/// \brief Look up the copying constructor for the given class.
2435CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002436 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002437 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2438 "non-const, non-volatile qualifiers for copy ctor arg");
2439 SpecialMemberOverloadResult *Result =
2440 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2441 Quals & Qualifiers::Volatile, false, false, false);
2442
Sean Huntc530d172011-06-10 04:44:37 +00002443 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2444}
2445
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002446/// \brief Look up the moving constructor for the given class.
2447CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2448 SpecialMemberOverloadResult *Result =
2449 LookupSpecialMember(Class, CXXMoveConstructor, false,
2450 false, false, false, false);
2451
2452 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2453}
2454
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002455/// \brief Look up the constructors for the given class.
2456DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002457 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002458 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002459 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002460 DeclareImplicitDefaultConstructor(Class);
2461 if (!Class->hasDeclaredCopyConstructor())
2462 DeclareImplicitCopyConstructor(Class);
David Blaikie4e4d0842012-03-11 07:00:24 +00002463 if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002464 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002465 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002466
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002467 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2468 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2469 return Class->lookup(Name);
2470}
2471
Sean Hunt661c67a2011-06-21 23:42:56 +00002472/// \brief Look up the copying assignment operator for the given class.
2473CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2474 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002475 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002476 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2477 "non-const, non-volatile qualifiers for copy assignment arg");
2478 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2479 "non-const, non-volatile qualifiers for copy assignment this");
2480 SpecialMemberOverloadResult *Result =
2481 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2482 Quals & Qualifiers::Volatile, RValueThis,
2483 ThisQuals & Qualifiers::Const,
2484 ThisQuals & Qualifiers::Volatile);
2485
Sean Hunt661c67a2011-06-21 23:42:56 +00002486 return Result->getMethod();
2487}
2488
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002489/// \brief Look up the moving assignment operator for the given class.
2490CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2491 bool RValueThis,
2492 unsigned ThisQuals) {
2493 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2494 "non-const, non-volatile qualifiers for copy assignment this");
2495 SpecialMemberOverloadResult *Result =
2496 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2497 ThisQuals & Qualifiers::Const,
2498 ThisQuals & Qualifiers::Volatile);
2499
2500 return Result->getMethod();
2501}
2502
Douglas Gregordb89f282010-07-01 22:47:18 +00002503/// \brief Look for the destructor of the given class.
2504///
Sean Huntc5c9b532011-06-03 21:10:40 +00002505/// During semantic analysis, this routine should be used in lieu of
2506/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002507///
2508/// \returns The destructor for this class.
2509CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002510 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2511 false, false, false,
2512 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002513}
2514
Richard Smith36f5cfe2012-03-09 08:00:36 +00002515/// LookupLiteralOperator - Determine which literal operator should be used for
2516/// a user-defined literal, per C++11 [lex.ext].
2517///
2518/// Normal overload resolution is not used to select which literal operator to
2519/// call for a user-defined literal. Look up the provided literal operator name,
2520/// and filter the results to the appropriate set for the given argument types.
2521Sema::LiteralOperatorLookupResult
2522Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2523 ArrayRef<QualType> ArgTys,
2524 bool AllowRawAndTemplate) {
2525 LookupName(R, S);
2526 assert(R.getResultKind() != LookupResult::Ambiguous &&
2527 "literal operator lookup can't be ambiguous");
2528
2529 // Filter the lookup results appropriately.
2530 LookupResult::Filter F = R.makeFilter();
2531
2532 bool FoundTemplate = false;
2533 bool FoundRaw = false;
2534 bool FoundExactMatch = false;
2535
2536 while (F.hasNext()) {
2537 Decl *D = F.next();
2538 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2539 D = USD->getTargetDecl();
2540
2541 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2542 bool IsRaw = false;
2543 bool IsExactMatch = false;
2544
2545 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2546 if (FD->getNumParams() == 1 &&
2547 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2548 IsRaw = true;
2549 else {
2550 IsExactMatch = true;
2551 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2552 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2553 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2554 IsExactMatch = false;
2555 break;
2556 }
2557 }
2558 }
2559 }
2560
2561 if (IsExactMatch) {
2562 FoundExactMatch = true;
2563 AllowRawAndTemplate = false;
2564 if (FoundRaw || FoundTemplate) {
2565 // Go through again and remove the raw and template decls we've
2566 // already found.
2567 F.restart();
2568 FoundRaw = FoundTemplate = false;
2569 }
2570 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2571 FoundTemplate |= IsTemplate;
2572 FoundRaw |= IsRaw;
2573 } else {
2574 F.erase();
2575 }
2576 }
2577
2578 F.done();
2579
2580 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2581 // parameter type, that is used in preference to a raw literal operator
2582 // or literal operator template.
2583 if (FoundExactMatch)
2584 return LOLR_Cooked;
2585
2586 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2587 // operator template, but not both.
2588 if (FoundRaw && FoundTemplate) {
2589 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2590 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2591 Decl *D = *I;
2592 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2593 D = USD->getTargetDecl();
2594 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2595 D = FunTmpl->getTemplatedDecl();
2596 NoteOverloadCandidate(cast<FunctionDecl>(D));
2597 }
2598 return LOLR_Error;
2599 }
2600
2601 if (FoundRaw)
2602 return LOLR_Raw;
2603
2604 if (FoundTemplate)
2605 return LOLR_Template;
2606
2607 // Didn't find anything we could use.
2608 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2609 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2610 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2611 return LOLR_Error;
2612}
2613
John McCall7edb5fd2010-01-26 07:16:45 +00002614void ADLResult::insert(NamedDecl *New) {
2615 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2616
2617 // If we haven't yet seen a decl for this key, or the last decl
2618 // was exactly this one, we're done.
2619 if (Old == 0 || Old == New) {
2620 Old = New;
2621 return;
2622 }
2623
2624 // Otherwise, decide which is a more recent redeclaration.
2625 FunctionDecl *OldFD, *NewFD;
2626 if (isa<FunctionTemplateDecl>(New)) {
2627 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2628 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2629 } else {
2630 OldFD = cast<FunctionDecl>(Old);
2631 NewFD = cast<FunctionDecl>(New);
2632 }
2633
2634 FunctionDecl *Cursor = NewFD;
2635 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002636 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002637
2638 // If we got to the end without finding OldFD, OldFD is the newer
2639 // declaration; leave things as they are.
2640 if (!Cursor) return;
2641
2642 // If we do find OldFD, then NewFD is newer.
2643 if (Cursor == OldFD) break;
2644
2645 // Otherwise, keep looking.
2646 }
2647
2648 Old = New;
2649}
2650
Sebastian Redl644be852009-10-23 19:23:15 +00002651void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00002652 SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002653 llvm::ArrayRef<Expr *> Args,
Richard Smithad762fc2011-04-14 22:09:26 +00002654 ADLResult &Result,
2655 bool StdNamespaceIsAssociated) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002656 // Find all of the associated namespaces and classes based on the
2657 // arguments we have.
2658 AssociatedNamespaceSet AssociatedNamespaces;
2659 AssociatedClassSet AssociatedClasses;
Ahmed Charles13a140c2012-02-25 11:00:22 +00002660 FindAssociatedClassesAndNamespaces(Args,
John McCall6ff07852009-08-07 22:18:02 +00002661 AssociatedNamespaces,
2662 AssociatedClasses);
Richard Smithad762fc2011-04-14 22:09:26 +00002663 if (StdNamespaceIsAssociated && StdNamespace)
2664 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002665
Sebastian Redl644be852009-10-23 19:23:15 +00002666 QualType T1, T2;
2667 if (Operator) {
2668 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002669 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002670 T2 = Args[1]->getType();
2671 }
2672
Richard Smithf5cd5cc2012-02-25 06:24:24 +00002673 // Try to complete all associated classes, in case they contain a
2674 // declaration of a friend function.
2675 for (AssociatedClassSet::iterator C = AssociatedClasses.begin(),
2676 CEnd = AssociatedClasses.end();
2677 C != CEnd; ++C)
2678 RequireCompleteType(Loc, Context.getRecordType(*C), 0);
2679
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002680 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002681 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2682 // and let Y be the lookup set produced by argument dependent
2683 // lookup (defined as follows). If X contains [...] then Y is
2684 // empty. Otherwise Y is the set of declarations found in the
2685 // namespaces associated with the argument types as described
2686 // below. The set of declarations found by the lookup of the name
2687 // is the union of X and Y.
2688 //
2689 // Here, we compute Y and add its members to the overloaded
2690 // candidate set.
2691 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002692 NSEnd = AssociatedNamespaces.end();
2693 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002694 // When considering an associated namespace, the lookup is the
2695 // same as the lookup performed when the associated namespace is
2696 // used as a qualifier (3.4.3.2) except that:
2697 //
2698 // -- Any using-directives in the associated namespace are
2699 // ignored.
2700 //
John McCall6ff07852009-08-07 22:18:02 +00002701 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002702 // associated classes are visible within their respective
2703 // namespaces even if they are not visible during an ordinary
2704 // lookup (11.4).
2705 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002706 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002707 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002708 // If the only declaration here is an ordinary friend, consider
2709 // it only if it was declared in an associated classes.
2710 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002711 DeclContext *LexDC = D->getLexicalDeclContext();
2712 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2713 continue;
2714 }
Mike Stump1eb44332009-09-09 15:08:12 +00002715
John McCalla113e722010-01-26 06:04:06 +00002716 if (isa<UsingShadowDecl>(D))
2717 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002718
John McCalla113e722010-01-26 06:04:06 +00002719 if (isa<FunctionDecl>(D)) {
2720 if (Operator &&
2721 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2722 T1, T2, Context))
2723 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002724 } else if (!isa<FunctionTemplateDecl>(D))
2725 continue;
2726
2727 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002728 }
2729 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002730}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002731
2732//----------------------------------------------------------------------------
2733// Search for all visible declarations.
2734//----------------------------------------------------------------------------
2735VisibleDeclConsumer::~VisibleDeclConsumer() { }
2736
2737namespace {
2738
2739class ShadowContextRAII;
2740
2741class VisibleDeclsRecord {
2742public:
2743 /// \brief An entry in the shadow map, which is optimized to store a
2744 /// single declaration (the common case) but can also store a list
2745 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002746 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002747
2748private:
2749 /// \brief A mapping from declaration names to the declarations that have
2750 /// this name within a particular scope.
2751 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2752
2753 /// \brief A list of shadow maps, which is used to model name hiding.
2754 std::list<ShadowMap> ShadowMaps;
2755
2756 /// \brief The declaration contexts we have already visited.
2757 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2758
2759 friend class ShadowContextRAII;
2760
2761public:
2762 /// \brief Determine whether we have already visited this context
2763 /// (and, if not, note that we are going to visit that context now).
2764 bool visitedContext(DeclContext *Ctx) {
2765 return !VisitedContexts.insert(Ctx);
2766 }
2767
Douglas Gregor8071e422010-08-15 06:18:01 +00002768 bool alreadyVisitedContext(DeclContext *Ctx) {
2769 return VisitedContexts.count(Ctx);
2770 }
2771
Douglas Gregor546be3c2009-12-30 17:04:44 +00002772 /// \brief Determine whether the given declaration is hidden in the
2773 /// current scope.
2774 ///
2775 /// \returns the declaration that hides the given declaration, or
2776 /// NULL if no such declaration exists.
2777 NamedDecl *checkHidden(NamedDecl *ND);
2778
2779 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002780 void add(NamedDecl *ND) {
2781 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2782 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002783};
2784
2785/// \brief RAII object that records when we've entered a shadow context.
2786class ShadowContextRAII {
2787 VisibleDeclsRecord &Visible;
2788
2789 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2790
2791public:
2792 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2793 Visible.ShadowMaps.push_back(ShadowMap());
2794 }
2795
2796 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002797 Visible.ShadowMaps.pop_back();
2798 }
2799};
2800
2801} // end anonymous namespace
2802
Douglas Gregor546be3c2009-12-30 17:04:44 +00002803NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002804 // Look through using declarations.
2805 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002806
Douglas Gregor546be3c2009-12-30 17:04:44 +00002807 unsigned IDNS = ND->getIdentifierNamespace();
2808 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2809 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2810 SM != SMEnd; ++SM) {
2811 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2812 if (Pos == SM->end())
2813 continue;
2814
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002815 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002816 IEnd = Pos->second.end();
2817 I != IEnd; ++I) {
2818 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002819 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002820 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002821 Decl::IDNS_ObjCProtocol)))
2822 continue;
2823
2824 // Protocols are in distinct namespaces from everything else.
2825 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2826 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2827 (*I)->getIdentifierNamespace() != IDNS)
2828 continue;
2829
Douglas Gregor0cc84042010-01-14 15:47:35 +00002830 // Functions and function templates in the same scope overload
2831 // rather than hide. FIXME: Look for hiding based on function
2832 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002833 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002834 ND->isFunctionOrFunctionTemplate() &&
2835 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002836 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002837
Douglas Gregor546be3c2009-12-30 17:04:44 +00002838 // We've found a declaration that hides this one.
2839 return *I;
2840 }
2841 }
2842
2843 return 0;
2844}
2845
2846static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2847 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002848 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002849 VisibleDeclConsumer &Consumer,
2850 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002851 if (!Ctx)
2852 return;
2853
Douglas Gregor546be3c2009-12-30 17:04:44 +00002854 // Make sure we don't visit the same context twice.
2855 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2856 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002857
Douglas Gregor4923aa22010-07-02 20:37:36 +00002858 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2859 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2860
Douglas Gregor546be3c2009-12-30 17:04:44 +00002861 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00002862 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2863 LEnd = Ctx->lookups_end();
2864 L != LEnd; ++L) {
2865 for (DeclContext::lookup_result R = *L; R.first != R.second; ++R.first) {
2866 if (NamedDecl *ND = dyn_cast<NamedDecl>(*R.first)) {
Douglas Gregor55368912011-12-14 16:03:29 +00002867 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002868 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002869 Visited.add(ND);
2870 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002871 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002872 }
2873 }
2874
2875 // Traverse using directives for qualified name lookup.
2876 if (QualifiedNameLookup) {
2877 ShadowContextRAII Shadow(Visited);
2878 DeclContext::udir_iterator I, E;
2879 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002880 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002881 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002882 }
2883 }
2884
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002885 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002886 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002887 if (!Record->hasDefinition())
2888 return;
2889
Douglas Gregor546be3c2009-12-30 17:04:44 +00002890 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2891 BEnd = Record->bases_end();
2892 B != BEnd; ++B) {
2893 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002894
Douglas Gregor546be3c2009-12-30 17:04:44 +00002895 // Don't look into dependent bases, because name lookup can't look
2896 // there anyway.
2897 if (BaseType->isDependentType())
2898 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002899
Douglas Gregor546be3c2009-12-30 17:04:44 +00002900 const RecordType *Record = BaseType->getAs<RecordType>();
2901 if (!Record)
2902 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002903
Douglas Gregor546be3c2009-12-30 17:04:44 +00002904 // FIXME: It would be nice to be able to determine whether referencing
2905 // a particular member would be ambiguous. For example, given
2906 //
2907 // struct A { int member; };
2908 // struct B { int member; };
2909 // struct C : A, B { };
2910 //
2911 // void f(C *c) { c->### }
2912 //
2913 // accessing 'member' would result in an ambiguity. However, we
2914 // could be smart enough to qualify the member with the base
2915 // class, e.g.,
2916 //
2917 // c->B::member
2918 //
2919 // or
2920 //
2921 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002922
Douglas Gregor546be3c2009-12-30 17:04:44 +00002923 // Find results in this base class (and its bases).
2924 ShadowContextRAII Shadow(Visited);
2925 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002926 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002927 }
2928 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002929
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002930 // Traverse the contexts of Objective-C classes.
2931 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2932 // Traverse categories.
2933 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2934 Category; Category = Category->getNextClassCategory()) {
2935 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002936 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002937 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002938 }
2939
2940 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002941 for (ObjCInterfaceDecl::all_protocol_iterator
2942 I = IFace->all_referenced_protocol_begin(),
2943 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002944 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002945 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002946 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002947 }
2948
2949 // Traverse the superclass.
2950 if (IFace->getSuperClass()) {
2951 ShadowContextRAII Shadow(Visited);
2952 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002953 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002954 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002955
Douglas Gregorc220a182010-04-19 18:02:19 +00002956 // If there is an implementation, traverse it. We do this to find
2957 // synthesized ivars.
2958 if (IFace->getImplementation()) {
2959 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002960 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00002961 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00002962 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002963 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2964 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2965 E = Protocol->protocol_end(); I != E; ++I) {
2966 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002967 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002968 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002969 }
2970 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2971 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2972 E = Category->protocol_end(); I != E; ++I) {
2973 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002974 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002975 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002976 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002977
Douglas Gregorc220a182010-04-19 18:02:19 +00002978 // If there is an implementation, traverse it.
2979 if (Category->getImplementation()) {
2980 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002981 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002982 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002983 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002984 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002985}
2986
2987static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2988 UnqualUsingDirectiveSet &UDirs,
2989 VisibleDeclConsumer &Consumer,
2990 VisibleDeclsRecord &Visited) {
2991 if (!S)
2992 return;
2993
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002994 if (!S->getEntity() ||
2995 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002996 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002997 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2998 // Walk through the declarations in this Scope.
2999 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3000 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003001 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003002 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003003 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003004 Visited.add(ND);
3005 }
3006 }
3007 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003008
Douglas Gregor711be1e2010-03-15 14:33:29 +00003009 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003010 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003011 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003012 // Look into this scope's declaration context, along with any of its
3013 // parent lookup contexts (e.g., enclosing classes), up to the point
3014 // where we hit the context stored in the next outer scope.
3015 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003016 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003017
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003018 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003019 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003020 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3021 if (Method->isInstanceMethod()) {
3022 // For instance methods, look for ivars in the method's interface.
3023 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3024 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003025 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003026 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00003027 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003028 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003029 }
3030
3031 // We've already performed all of the name lookup that we need
3032 // to for Objective-C methods; the next context will be the
3033 // outer scope.
3034 break;
3035 }
3036
Douglas Gregor546be3c2009-12-30 17:04:44 +00003037 if (Ctx->isFunctionOrMethod())
3038 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003039
3040 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003041 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003042 }
3043 } else if (!S->getParent()) {
3044 // Look into the translation unit scope. We walk through the translation
3045 // unit's declaration context, because the Scope itself won't have all of
3046 // the declarations if we loaded a precompiled header.
3047 // FIXME: We would like the translation unit's Scope object to point to the
3048 // translation unit, so we don't need this special "if" branch. However,
3049 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003050 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003051 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003052 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003053 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003054 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003055 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003056 }
3057
Douglas Gregor546be3c2009-12-30 17:04:44 +00003058 if (Entity) {
3059 // Lookup visible declarations in any namespaces found by using
3060 // directives.
3061 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3062 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3063 for (; UI != UEnd; ++UI)
3064 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003065 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003066 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003067 }
3068
3069 // Lookup names in the parent scope.
3070 ShadowContextRAII Shadow(Visited);
3071 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3072}
3073
3074void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003075 VisibleDeclConsumer &Consumer,
3076 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003077 // Determine the set of using directives available during
3078 // unqualified name lookup.
3079 Scope *Initial = S;
3080 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003081 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003082 // Find the first namespace or translation-unit scope.
3083 while (S && !isNamespaceOrTranslationUnitScope(S))
3084 S = S->getParent();
3085
3086 UDirs.visitScopeChain(Initial, S);
3087 }
3088 UDirs.done();
3089
3090 // Look for visible declarations.
3091 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3092 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003093 if (!IncludeGlobalScope)
3094 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003095 ShadowContextRAII Shadow(Visited);
3096 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3097}
3098
3099void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003100 VisibleDeclConsumer &Consumer,
3101 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003102 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3103 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003104 if (!IncludeGlobalScope)
3105 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003106 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003107 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003108 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003109}
3110
Chris Lattner4ae493c2011-02-18 02:08:43 +00003111/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003112/// If GnuLabelLoc is a valid source location, then this is a definition
3113/// of an __label__ label name, otherwise it is a normal label definition
3114/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003115LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003116 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003117 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003118 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003119
3120 if (GnuLabelLoc.isValid()) {
3121 // Local label definitions always shadow existing labels.
3122 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3123 Scope *S = CurScope;
3124 PushOnScopeChains(Res, S, true);
3125 return cast<LabelDecl>(Res);
3126 }
3127
3128 // Not a GNU local label.
3129 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3130 // If we found a label, check to see if it is in the same context as us.
3131 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003132 if (Res && Res->getDeclContext() != CurContext)
3133 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003134 if (Res == 0) {
3135 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003136 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3137 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003138 assert(S && "Not in a function?");
3139 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003140 }
Chris Lattner337e5502011-02-18 01:27:55 +00003141 return cast<LabelDecl>(Res);
3142}
3143
3144//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003145// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003146//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003147
3148namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003149
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003150typedef llvm::SmallVector<TypoCorrection, 1> TypoResultList;
3151typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003152typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003153
3154static const unsigned MaxTypoDistanceResultSets = 5;
3155
Douglas Gregor546be3c2009-12-30 17:04:44 +00003156class TypoCorrectionConsumer : public VisibleDeclConsumer {
3157 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003158 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003159
3160 /// \brief The results found that have the smallest edit distance
3161 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003162 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003163 /// The pointer value being set to the current DeclContext indicates
3164 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003165 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003166
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003167 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003168
Douglas Gregor546be3c2009-12-30 17:04:44 +00003169public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003170 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003171 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003172 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003173
Erik Verbruggend1205962011-10-06 07:27:49 +00003174 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3175 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003176 void FoundName(StringRef Name);
3177 void addKeywordResult(StringRef Keyword);
3178 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003179 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003180 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003181
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003182 typedef TypoResultsMap::iterator result_iterator;
3183 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003184 distance_iterator begin() { return CorrectionResults.begin(); }
3185 distance_iterator end() { return CorrectionResults.end(); }
3186 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3187 unsigned size() const { return CorrectionResults.size(); }
3188 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003189
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003190 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003191 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003192 }
3193
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003194 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003195 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003196 return (std::numeric_limits<unsigned>::max)();
3197
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003198 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003199 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003200 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003201
3202 TypoResultsMap &getBestResults() {
3203 return CorrectionResults.begin()->second;
3204 }
3205
Douglas Gregor546be3c2009-12-30 17:04:44 +00003206};
3207
3208}
3209
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003210void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003211 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003212 // Don't consider hidden names for typo correction.
3213 if (Hiding)
3214 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215
Douglas Gregor546be3c2009-12-30 17:04:44 +00003216 // Only consider entities with identifiers for names, ignoring
3217 // special names (constructors, overloaded operators, selectors,
3218 // etc.).
3219 IdentifierInfo *Name = ND->getIdentifier();
3220 if (!Name)
3221 return;
3222
Douglas Gregor95f42922010-10-14 22:11:03 +00003223 FoundName(Name->getName());
3224}
3225
Chris Lattner5f9e2722011-07-23 10:55:15 +00003226void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003227 // Use a simple length-based heuristic to determine the minimum possible
3228 // edit distance. If the minimum isn't good enough, bail out early.
3229 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003230 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003231 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003232
Douglas Gregora1194772010-10-19 22:14:33 +00003233 // Compute an upper bound on the allowable edit distance, so that the
3234 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003235 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003236
Douglas Gregor546be3c2009-12-30 17:04:44 +00003237 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003238 // entity, and add the identifier to the list of results.
3239 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003240}
3241
Chris Lattner5f9e2722011-07-23 10:55:15 +00003242void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003243 // Compute the edit distance between the typo and this keyword,
3244 // and add the keyword to the list of results.
3245 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003246}
3247
Chris Lattner5f9e2722011-07-23 10:55:15 +00003248void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003249 NamedDecl *ND,
3250 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003251 NestedNameSpecifier *NNS,
3252 bool isKeyword) {
3253 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3254 if (isKeyword) TC.makeKeyword();
3255 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003256}
3257
3258void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003259 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003260 TypoResultList &CList =
3261 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003262
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003263 if (!CList.empty() && !CList.back().isResolved())
3264 CList.pop_back();
3265 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3266 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3267 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3268 RI != RIEnd; ++RI) {
3269 // If the Correction refers to a decl already in the result list,
3270 // replace the existing result if the string representation of Correction
3271 // comes before the current result alphabetically, then stop as there is
3272 // nothing more to be done to add Correction to the candidate set.
3273 if (RI->getCorrectionDecl() == NewND) {
3274 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3275 *RI = Correction;
3276 return;
3277 }
3278 }
3279 }
3280 if (CList.empty() || Correction.isResolved())
3281 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003282
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003283 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3284 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003285}
3286
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003287// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3288// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3289// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3290static void getNestedNameSpecifierIdentifiers(
3291 NestedNameSpecifier *NNS,
3292 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3293 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3294 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3295 else
3296 Identifiers.clear();
3297
3298 const IdentifierInfo *II = NULL;
3299
3300 switch (NNS->getKind()) {
3301 case NestedNameSpecifier::Identifier:
3302 II = NNS->getAsIdentifier();
3303 break;
3304
3305 case NestedNameSpecifier::Namespace:
3306 if (NNS->getAsNamespace()->isAnonymousNamespace())
3307 return;
3308 II = NNS->getAsNamespace()->getIdentifier();
3309 break;
3310
3311 case NestedNameSpecifier::NamespaceAlias:
3312 II = NNS->getAsNamespaceAlias()->getIdentifier();
3313 break;
3314
3315 case NestedNameSpecifier::TypeSpecWithTemplate:
3316 case NestedNameSpecifier::TypeSpec:
3317 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3318 break;
3319
3320 case NestedNameSpecifier::Global:
3321 return;
3322 }
3323
3324 if (II)
3325 Identifiers.push_back(II);
3326}
3327
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003328namespace {
3329
3330class SpecifierInfo {
3331 public:
3332 DeclContext* DeclCtx;
3333 NestedNameSpecifier* NameSpecifier;
3334 unsigned EditDistance;
3335
3336 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3337 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3338};
3339
Chris Lattner5f9e2722011-07-23 10:55:15 +00003340typedef SmallVector<DeclContext*, 4> DeclContextList;
3341typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003342
3343class NamespaceSpecifierSet {
3344 ASTContext &Context;
3345 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003346 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3347 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003348 bool isSorted;
3349
3350 SpecifierInfoList Specifiers;
3351 llvm::SmallSetVector<unsigned, 4> Distances;
3352 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3353
3354 /// \brief Helper for building the list of DeclContexts between the current
3355 /// context and the top of the translation unit
3356 static DeclContextList BuildContextChain(DeclContext *Start);
3357
3358 void SortNamespaces();
3359
3360 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003361 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3362 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003363 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003364 isSorted(true) {
3365 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3366 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3367 CurNameSpecifierIdentifiers);
3368 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003369 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003370 // context.
3371 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3372 CEnd = CurContextChain.rend();
3373 C != CEnd; ++C) {
3374 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3375 CurContextIdentifiers.push_back(ND->getIdentifier());
3376 }
3377 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003378
3379 /// \brief Add the namespace to the set, computing the corresponding
3380 /// NestedNameSpecifier and its distance in the process.
3381 void AddNamespace(NamespaceDecl *ND);
3382
3383 typedef SpecifierInfoList::iterator iterator;
3384 iterator begin() {
3385 if (!isSorted) SortNamespaces();
3386 return Specifiers.begin();
3387 }
3388 iterator end() { return Specifiers.end(); }
3389};
3390
3391}
3392
3393DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003394 assert(Start && "Bulding a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003395 DeclContextList Chain;
3396 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3397 DC = DC->getLookupParent()) {
3398 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3399 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3400 !(ND && ND->isAnonymousNamespace()))
3401 Chain.push_back(DC->getPrimaryContext());
3402 }
3403 return Chain;
3404}
3405
3406void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003407 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003408 sortedDistances.append(Distances.begin(), Distances.end());
3409
3410 if (sortedDistances.size() > 1)
3411 std::sort(sortedDistances.begin(), sortedDistances.end());
3412
3413 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003414 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003415 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003416 DI != DIEnd; ++DI) {
3417 SpecifierInfoList &SpecList = DistanceMap[*DI];
3418 Specifiers.append(SpecList.begin(), SpecList.end());
3419 }
3420
3421 isSorted = true;
3422}
3423
3424void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003425 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003426 NestedNameSpecifier *NNS = NULL;
3427 unsigned NumSpecifiers = 0;
3428 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003429 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003430
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003431 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003432 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3433 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003434 C != CEnd && !NamespaceDeclChain.empty() &&
3435 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003436 NamespaceDeclChain.pop_back();
3437 }
3438
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003439 // Add an explicit leading '::' specifier if needed.
3440 if (NamespaceDecl *ND =
Kaelyn Uhrain3ad02aa2012-02-15 22:59:03 +00003441 NamespaceDeclChain.empty() ? NULL :
3442 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003443 IdentifierInfo *Name = ND->getIdentifier();
3444 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3445 Name) != CurContextIdentifiers.end() ||
3446 std::find(CurNameSpecifierIdentifiers.begin(),
3447 CurNameSpecifierIdentifiers.end(),
3448 Name) != CurNameSpecifierIdentifiers.end()) {
3449 NamespaceDeclChain = FullNamespaceDeclChain;
3450 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3451 }
3452 }
3453
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003454 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3455 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3456 CEnd = NamespaceDeclChain.rend();
3457 C != CEnd; ++C) {
3458 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3459 if (ND) {
3460 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3461 ++NumSpecifiers;
3462 }
3463 }
3464
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003465 // If the built NestedNameSpecifier would be replacing an existing
3466 // NestedNameSpecifier, use the number of component identifiers that
3467 // would need to be changed as the edit distance instead of the number
3468 // of components in the built NestedNameSpecifier.
3469 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3470 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3471 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3472 NumSpecifiers = llvm::ComputeEditDistance(
3473 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3474 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3475 }
3476
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003477 isSorted = false;
3478 Distances.insert(NumSpecifiers);
3479 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003480}
3481
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003482/// \brief Perform name lookup for a possible result for typo correction.
3483static void LookupPotentialTypoResult(Sema &SemaRef,
3484 LookupResult &Res,
3485 IdentifierInfo *Name,
3486 Scope *S, CXXScopeSpec *SS,
3487 DeclContext *MemberContext,
3488 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003489 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003490 Res.suppressDiagnostics();
3491 Res.clear();
3492 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003493 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003494 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003495 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003496 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3497 Res.addDecl(Ivar);
3498 Res.resolveKind();
3499 return;
3500 }
3501 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003502
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003503 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3504 Res.addDecl(Prop);
3505 Res.resolveKind();
3506 return;
3507 }
3508 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003509
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003510 SemaRef.LookupQualifiedName(Res, MemberContext);
3511 return;
3512 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003513
3514 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003515 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003516
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003517 // Fake ivar lookup; this should really be part of
3518 // LookupParsedName.
3519 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3520 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003521 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003522 (Res.isSingleResult() &&
3523 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003524 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003525 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3526 Res.addDecl(IV);
3527 Res.resolveKind();
3528 }
3529 }
3530 }
3531}
3532
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003533/// \brief Add keywords to the consumer as possible typo corrections.
3534static void AddKeywordsToConsumer(Sema &SemaRef,
3535 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003536 Scope *S, CorrectionCandidateCallback &CCC,
3537 bool AfterNestedNameSpecifier) {
3538 if (AfterNestedNameSpecifier) {
3539 // For 'X::', we know exactly which keywords can appear next.
3540 Consumer.addKeywordResult("template");
3541 if (CCC.WantExpressionKeywords)
3542 Consumer.addKeywordResult("operator");
3543 return;
3544 }
3545
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003546 if (CCC.WantObjCSuper)
3547 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003548
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003549 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003550 // Add type-specifier keywords to the set of results.
3551 const char *CTypeSpecs[] = {
3552 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003553 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003554 "_Complex", "_Imaginary",
3555 // storage-specifiers as well
3556 "extern", "inline", "static", "typedef"
3557 };
3558
3559 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3560 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3561 Consumer.addKeywordResult(CTypeSpecs[I]);
3562
David Blaikie4e4d0842012-03-11 07:00:24 +00003563 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003564 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003565 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003566 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003567 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003568 Consumer.addKeywordResult("_Bool");
3569
David Blaikie4e4d0842012-03-11 07:00:24 +00003570 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003571 Consumer.addKeywordResult("class");
3572 Consumer.addKeywordResult("typename");
3573 Consumer.addKeywordResult("wchar_t");
3574
David Blaikie4e4d0842012-03-11 07:00:24 +00003575 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003576 Consumer.addKeywordResult("char16_t");
3577 Consumer.addKeywordResult("char32_t");
3578 Consumer.addKeywordResult("constexpr");
3579 Consumer.addKeywordResult("decltype");
3580 Consumer.addKeywordResult("thread_local");
3581 }
3582 }
3583
David Blaikie4e4d0842012-03-11 07:00:24 +00003584 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003585 Consumer.addKeywordResult("typeof");
3586 }
3587
David Blaikie4e4d0842012-03-11 07:00:24 +00003588 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003589 Consumer.addKeywordResult("const_cast");
3590 Consumer.addKeywordResult("dynamic_cast");
3591 Consumer.addKeywordResult("reinterpret_cast");
3592 Consumer.addKeywordResult("static_cast");
3593 }
3594
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003595 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003596 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003597 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003598 Consumer.addKeywordResult("false");
3599 Consumer.addKeywordResult("true");
3600 }
3601
David Blaikie4e4d0842012-03-11 07:00:24 +00003602 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003603 const char *CXXExprs[] = {
3604 "delete", "new", "operator", "throw", "typeid"
3605 };
3606 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3607 for (unsigned I = 0; I != NumCXXExprs; ++I)
3608 Consumer.addKeywordResult(CXXExprs[I]);
3609
3610 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3611 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3612 Consumer.addKeywordResult("this");
3613
David Blaikie4e4d0842012-03-11 07:00:24 +00003614 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003615 Consumer.addKeywordResult("alignof");
3616 Consumer.addKeywordResult("nullptr");
3617 }
3618 }
3619 }
3620
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003621 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003622 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3623 // Statements.
3624 const char *CStmts[] = {
3625 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3626 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3627 for (unsigned I = 0; I != NumCStmts; ++I)
3628 Consumer.addKeywordResult(CStmts[I]);
3629
David Blaikie4e4d0842012-03-11 07:00:24 +00003630 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003631 Consumer.addKeywordResult("catch");
3632 Consumer.addKeywordResult("try");
3633 }
3634
3635 if (S && S->getBreakParent())
3636 Consumer.addKeywordResult("break");
3637
3638 if (S && S->getContinueParent())
3639 Consumer.addKeywordResult("continue");
3640
3641 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3642 Consumer.addKeywordResult("case");
3643 Consumer.addKeywordResult("default");
3644 }
3645 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003646 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003647 Consumer.addKeywordResult("namespace");
3648 Consumer.addKeywordResult("template");
3649 }
3650
3651 if (S && S->isClassScope()) {
3652 Consumer.addKeywordResult("explicit");
3653 Consumer.addKeywordResult("friend");
3654 Consumer.addKeywordResult("mutable");
3655 Consumer.addKeywordResult("private");
3656 Consumer.addKeywordResult("protected");
3657 Consumer.addKeywordResult("public");
3658 Consumer.addKeywordResult("virtual");
3659 }
3660 }
3661
David Blaikie4e4d0842012-03-11 07:00:24 +00003662 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003663 Consumer.addKeywordResult("using");
3664
David Blaikie4e4d0842012-03-11 07:00:24 +00003665 if (SemaRef.getLangOpts().CPlusPlus0x)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003666 Consumer.addKeywordResult("static_assert");
3667 }
3668 }
3669}
3670
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003671static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3672 TypoCorrection &Candidate) {
3673 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3674 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3675}
3676
Douglas Gregor546be3c2009-12-30 17:04:44 +00003677/// \brief Try to "correct" a typo in the source code by finding
3678/// visible declarations whose names are similar to the name that was
3679/// present in the source code.
3680///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003681/// \param TypoName the \c DeclarationNameInfo structure that contains
3682/// the name that was present in the source code along with its location.
3683///
3684/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003685///
3686/// \param S the scope in which name lookup occurs.
3687///
3688/// \param SS the nested-name-specifier that precedes the name we're
3689/// looking for, if present.
3690///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003691/// \param CCC A CorrectionCandidateCallback object that provides further
3692/// validation of typo correction candidates. It also provides flags for
3693/// determining the set of keywords permitted.
3694///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003695/// \param MemberContext if non-NULL, the context in which to look for
3696/// a member access expression.
3697///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003698/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003699/// the nested-name-specifier SS.
3700///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003701/// \param OPT when non-NULL, the search for visible declarations will
3702/// also walk the protocols in the qualified interfaces of \p OPT.
3703///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003704/// \returns a \c TypoCorrection containing the corrected name if the typo
3705/// along with information such as the \c NamedDecl where the corrected name
3706/// was declared, and any additional \c NestedNameSpecifier needed to access
3707/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3708TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3709 Sema::LookupNameKind LookupKind,
3710 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003711 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003712 DeclContext *MemberContext,
3713 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003714 const ObjCObjectPointerType *OPT) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003715 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003716 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003717
Francois Pichet4d604d62011-12-03 15:55:29 +00003718 // In Microsoft mode, don't perform typo correction in a template member
3719 // function dependent context because it interferes with the "lookup into
3720 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003721 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003722 isa<CXXMethodDecl>(CurContext))
3723 return TypoCorrection();
3724
Douglas Gregor546be3c2009-12-30 17:04:44 +00003725 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003726 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003727 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003728 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003729
3730 // If the scope specifier itself was invalid, don't try to correct
3731 // typos.
3732 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003733 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003734
3735 // Never try to correct typos during template deduction or
3736 // instantiation.
3737 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003738 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003739
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003740 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003741
3742 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003743
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003744 // If a callback object considers an empty typo correction candidate to be
3745 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003746 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003747 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003748
Douglas Gregoraaf87162010-04-14 20:04:41 +00003749 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003750 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003751 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003752 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003753 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003754
3755 // Look in qualified interfaces.
3756 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003757 for (ObjCObjectPointerType::qual_iterator
3758 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003759 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003760 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003761 }
3762 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003763 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3764 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003765 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003766
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003767 // Provide a stop gap for files that are just seriously broken. Trying
3768 // to correct all typos can turn into a HUGE performance penalty, causing
3769 // some files to take minutes to get rejected by the parser.
3770 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003771 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003772 ++TyposCorrected;
3773
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003774 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003775 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003776 IsUnqualifiedLookup = true;
3777 UnqualifiedTyposCorrectedMap::iterator Cached
3778 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003779 if (Cached != UnqualifiedTyposCorrected.end()) {
3780 // Add the cached value, unless it's a keyword or fails validation. In the
3781 // keyword case, we'll end up adding the keyword below.
3782 if (Cached->second) {
3783 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003784 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003785 Consumer.addCorrection(Cached->second);
3786 } else {
3787 // Only honor no-correction cache hits when a callback that will validate
3788 // correction candidates is not being used.
3789 if (!ValidatingCallback)
3790 return TypoCorrection();
3791 }
3792 }
3793 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003794 // Provide a stop gap for files that are just seriously broken. Trying
3795 // to correct all typos can turn into a HUGE performance penalty, causing
3796 // some files to take minutes to get rejected by the parser.
3797 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003798 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003799 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003800 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003801
Douglas Gregor01798682012-03-26 16:54:18 +00003802 // Determine whether we are going to search in the various namespaces for
3803 // corrections.
3804 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00003805 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00003806 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003807 // In a few cases we *only* want to search for corrections bases on just
3808 // adding or changing the nested name specifier.
3809 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00003810
3811 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003812 // For unqualified lookup, look through all of the names that we have
3813 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003814 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003815 for (IdentifierTable::iterator I = Context.Idents.begin(),
3816 IEnd = Context.Idents.end();
3817 I != IEnd; ++I)
3818 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003819
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003820 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003821 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003822 if (IdentifierInfoLookup *External
3823 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003824 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003825 do {
3826 StringRef Name = Iter->Next();
3827 if (Name.empty())
3828 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003829
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003830 Consumer.FoundName(Name);
3831 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00003832 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003833 }
3834
Richard Smith0f4b5be2012-06-08 21:35:42 +00003835 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003836
Douglas Gregoraaf87162010-04-14 20:04:41 +00003837 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003838 if (Consumer.empty()) {
3839 // If this was an unqualified lookup, note that no correction was found.
3840 if (IsUnqualifiedLookup)
3841 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003843 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003844 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003845
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003846 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3847 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003848 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003849 if (ED > 0 && Typo->getName().size() / ED < 3) {
3850 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003851 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003852 (void)UnqualifiedTyposCorrected[Typo];
3853
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003854 return TypoCorrection();
3855 }
3856
Douglas Gregor01798682012-03-26 16:54:18 +00003857 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3858 // to search those namespaces.
3859 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003860 // Load any externally-known namespaces.
3861 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003862 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003863 LoadedExternalKnownNamespaces = true;
3864 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3865 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3866 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3867 }
3868
3869 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3870 KNI = KnownNamespaces.begin(),
3871 KNIEnd = KnownNamespaces.end();
3872 KNI != KNIEnd; ++KNI)
3873 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003874 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003875
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003876 // Weed out any names that could not be found by name lookup or, if a
3877 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003878 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003879 LookupResult TmpRes(*this, TypoName, LookupKind);
3880 TmpRes.suppressDiagnostics();
3881 while (!Consumer.empty()) {
3882 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3883 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003884 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3885 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003886 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003887 // If we only want nested name specifier corrections, ignore potential
3888 // corrections that have a different base identifier from the typo.
3889 if (AllowOnlyNNSChanges &&
3890 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3891 TypoCorrectionConsumer::result_iterator Prev = I;
3892 ++I;
3893 DI->second.erase(Prev);
3894 continue;
3895 }
3896
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003897 // If the item already has been looked up or is a keyword, keep it.
3898 // If a validator callback object was given, drop the correction
3899 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003900 bool Viable = false;
3901 for (TypoResultList::iterator RI = I->second.begin(), RIEnd = I->second.end();
3902 RI != RIEnd; /* Increment in loop. */) {
3903 TypoResultList::iterator Prev = RI;
3904 ++RI;
3905 if (Prev->isResolved()) {
3906 if (!isCandidateViable(CCC, *Prev))
3907 I->second.erase(Prev);
3908 else
3909 Viable = true;
3910 }
3911 }
3912 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003913 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003914 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003915 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003916 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003917 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003918 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003919 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003920
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003921 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003922 TypoCorrection &Candidate = I->second.front();
3923 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003924 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003925 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003926
3927 switch (TmpRes.getResultKind()) {
3928 case LookupResult::NotFound:
3929 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003930 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003931 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003932 // We didn't find this name in our scope, or didn't like what we found;
3933 // ignore it.
3934 {
3935 TypoCorrectionConsumer::result_iterator Next = I;
3936 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003937 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003938 I = Next;
3939 }
3940 break;
3941
3942 case LookupResult::Ambiguous:
3943 // We don't deal with ambiguities.
3944 return TypoCorrection();
3945
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003946 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003947 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003948 // Store all of the Decls for overloaded symbols
3949 for (LookupResult::iterator TRD = TmpRes.begin(),
3950 TRDEnd = TmpRes.end();
3951 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003952 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003953 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003954 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003955 DI->second.erase(Prev);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003956 break;
3957 }
3958
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003959 case LookupResult::Found: {
3960 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003961 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003962 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003963 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003964 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003965 break;
3966 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003967
3968 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003969 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003970
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003971 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003972 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00003973 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003974 // If there are results in the closest possible bucket, stop
3975 break;
3976
3977 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00003978 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003979 TmpRes.suppressDiagnostics();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003980 for (llvm::SmallVector<TypoCorrection,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003981 16>::iterator QRI = QualifiedResults.begin(),
3982 QRIEnd = QualifiedResults.end();
3983 QRI != QRIEnd; ++QRI) {
3984 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3985 NIEnd = Namespaces.end();
3986 NI != NIEnd; ++NI) {
3987 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003988
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003989 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003990 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003991 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003992
3993 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003994 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003995 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3996
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003997 // Any corrections added below will be validated in subsequent
3998 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003999 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004000 case LookupResult::Found: {
4001 TypoCorrection TC(*QRI);
4002 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
4003 TC.setCorrectionSpecifier(NI->NameSpecifier);
4004 TC.setQualifierDistance(NI->EditDistance);
4005 Consumer.addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004006 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004007 }
4008 case LookupResult::FoundOverloaded: {
4009 TypoCorrection TC(*QRI);
4010 TC.setCorrectionSpecifier(NI->NameSpecifier);
4011 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004012 for (LookupResult::iterator TRD = TmpRes.begin(),
4013 TRDEnd = TmpRes.end();
4014 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004015 TC.addCorrectionDecl(*TRD);
4016 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004017 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004018 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004019 case LookupResult::NotFound:
4020 case LookupResult::NotFoundInCurrentInstantiation:
4021 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004022 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004023 break;
4024 }
4025 }
4026 }
4027 }
4028
4029 QualifiedResults.clear();
4030 }
4031
4032 // No corrections remain...
4033 if (Consumer.empty()) return TypoCorrection();
4034
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004035 TypoResultsMap &BestResults = Consumer.getBestResults();
4036 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004037
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004038 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004039 // If this was an unqualified lookup and we believe the callback
4040 // object wouldn't have filtered out possible corrections, note
4041 // that no correction was found.
4042 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004043 (void)UnqualifiedTyposCorrected[Typo];
4044
4045 return TypoCorrection();
4046 }
4047
Douglas Gregore24b5752010-10-14 20:34:08 +00004048 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004049 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004050 const TypoResultList &CorrectionList = BestResults.begin()->second;
4051 const TypoCorrection &Result = CorrectionList.front();
4052 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004053
Douglas Gregor53e4b552010-10-26 17:18:00 +00004054 // Don't correct to a keyword that's the same as the typo; the keyword
4055 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004056 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4057
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004058 // Record the correction for unqualified lookup.
4059 if (IsUnqualifiedLookup)
4060 UnqualifiedTyposCorrected[Typo] = Result;
4061
4062 return Result;
4063 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004064 else if (BestResults.size() > 1
4065 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4066 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4067 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4068 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004069 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004070 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004071 // Prefer 'super' when we're completing in a message-receiver
4072 // context.
4073
4074 // Don't correct to a keyword that's the same as the typo; the keyword
4075 // wasn't actually in scope.
4076 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004077
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004078 // Record the correction for unqualified lookup.
4079 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004080 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004081
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004082 return BestResults["super"].front();
Douglas Gregor7b824e82010-10-15 13:35:25 +00004083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004084
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004085 // If this was an unqualified lookup and we believe the callback object did
4086 // not filter out possible corrections, note that no correction was found.
4087 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004088 (void)UnqualifiedTyposCorrected[Typo];
4089
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004090 return TypoCorrection();
4091}
4092
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004093void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4094 if (!CDecl) return;
4095
4096 if (isKeyword())
4097 CorrectionDecls.clear();
4098
4099 CorrectionDecls.push_back(CDecl);
4100
4101 if (!CorrectionName)
4102 CorrectionName = CDecl->getDeclName();
4103}
4104
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004105std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4106 if (CorrectionNameSpec) {
4107 std::string tmpBuffer;
4108 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4109 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004110 CorrectionName.printName(PrefixOStream);
4111 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004112 }
4113
4114 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004115}