blob: 2206bd0b7890a4fe2b01bce1307ae8d152fb1490 [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:
James Dennett7ba75922012-06-19 21:05:49 +00001234/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001235/// (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.
James Dennett7ba75922012-06-19 21:05:49 +00001247///
John McCall6e247262009-10-10 05:48:19 +00001248/// C++98 [namespace.qual]p5:
1249/// During the lookup of a qualified namespace member name, if the
1250/// lookup finds more than one declaration of the member, and if one
1251/// declaration introduces a class name or enumeration name and the
1252/// other declarations either introduce the same object, the same
1253/// enumerator or a set of functions, the non-type name hides the
1254/// class or enumeration name if and only if the declarations are
1255/// from the same namespace; otherwise (the declarations are from
1256/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001257static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001258 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001259 assert(StartDC->isFileContext() && "start context is not a file context");
1260
1261 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1262 DeclContext::udir_iterator E = StartDC->using_directives_end();
1263
1264 if (I == E) return false;
1265
1266 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001267 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001268 Visited.insert(StartDC);
1269
1270 // We have not yet looked into these namespaces, much less added
1271 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001272 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001273
1274 // We have already looked into the initial namespace; seed the queue
1275 // with its using-children.
1276 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001277 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001278 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001279 Queue.push_back(ND);
1280 }
1281
1282 // The easiest way to implement the restriction in [namespace.qual]p5
1283 // is to check whether any of the individual results found a tag
1284 // and, if so, to declare an ambiguity if the final result is not
1285 // a tag.
1286 bool FoundTag = false;
1287 bool FoundNonTag = false;
1288
John McCall7d384dd2009-11-18 07:57:50 +00001289 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001290
1291 bool Found = false;
1292 while (!Queue.empty()) {
1293 NamespaceDecl *ND = Queue.back();
1294 Queue.pop_back();
1295
1296 // We go through some convolutions here to avoid copying results
1297 // between LookupResults.
1298 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001299 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001300 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001301
1302 if (FoundDirect) {
1303 // First do any local hiding.
1304 DirectR.resolveKind();
1305
1306 // If the local result is a tag, remember that.
1307 if (DirectR.isSingleTagDecl())
1308 FoundTag = true;
1309 else
1310 FoundNonTag = true;
1311
1312 // Append the local results to the total results if necessary.
1313 if (UseLocal) {
1314 R.addAllDecls(LocalR);
1315 LocalR.clear();
1316 }
1317 }
1318
1319 // If we find names in this namespace, ignore its using directives.
1320 if (FoundDirect) {
1321 Found = true;
1322 continue;
1323 }
1324
1325 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1326 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001327 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001328 Queue.push_back(Nom);
1329 }
1330 }
1331
1332 if (Found) {
1333 if (FoundTag && FoundNonTag)
1334 R.setAmbiguousQualifiedTagHiding();
1335 else
1336 R.resolveKind();
1337 }
1338
1339 return Found;
1340}
1341
Douglas Gregor8071e422010-08-15 06:18:01 +00001342/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001343static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001344 CXXBasePath &Path,
1345 void *Name) {
1346 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001347
Douglas Gregor8071e422010-08-15 06:18:01 +00001348 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1349 Path.Decls = BaseRecord->lookup(N);
1350 return Path.Decls.first != Path.Decls.second;
1351}
1352
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001353/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001354/// static members, nested types, and enumerators.
1355template<typename InputIterator>
1356static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1357 Decl *D = (*First)->getUnderlyingDecl();
1358 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1359 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001360
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001361 if (isa<CXXMethodDecl>(D)) {
1362 // Determine whether all of the methods are static.
1363 bool AllMethodsAreStatic = true;
1364 for(; First != Last; ++First) {
1365 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001366
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001367 if (!isa<CXXMethodDecl>(D)) {
1368 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1369 break;
1370 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001371
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001372 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1373 AllMethodsAreStatic = false;
1374 break;
1375 }
1376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001377
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001378 if (AllMethodsAreStatic)
1379 return true;
1380 }
1381
1382 return false;
1383}
1384
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001385/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001386///
1387/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1388/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001389/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001390///
1391/// Different lookup criteria can find different names. For example, a
1392/// particular scope can have both a struct and a function of the same
1393/// name, and each can be found by certain lookup criteria. For more
1394/// information about lookup criteria, see the documentation for the
1395/// class LookupCriteria.
1396///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001397/// \param R captures both the lookup criteria and any lookup results found.
1398///
1399/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001400/// search. If the lookup criteria permits, name lookup may also search
1401/// in the parent contexts or (for C++ classes) base classes.
1402///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001403/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001404/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001405///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001406/// \returns true if lookup succeeded, false if it failed.
1407bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1408 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001409 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001410
John McCalla24dc2e2009-11-17 02:14:36 +00001411 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001412 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001414 // Make sure that the declaration context is complete.
1415 assert((!isa<TagDecl>(LookupCtx) ||
1416 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001417 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001418 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001419 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001421 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001422 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001423 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001424 if (isa<CXXRecordDecl>(LookupCtx))
1425 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001426 return true;
1427 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001428
John McCall6e247262009-10-10 05:48:19 +00001429 // Don't descend into implied contexts for redeclarations.
1430 // C++98 [namespace.qual]p6:
1431 // In a declaration for a namespace member in which the
1432 // declarator-id is a qualified-id, given that the qualified-id
1433 // for the namespace member has the form
1434 // nested-name-specifier unqualified-id
1435 // the unqualified-id shall name a member of the namespace
1436 // designated by the nested-name-specifier.
1437 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001438 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001439 return false;
1440
John McCalla24dc2e2009-11-17 02:14:36 +00001441 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001442 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001443 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001444
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001445 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001446 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001447 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001448 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001449 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001450
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001451 // If we're performing qualified name lookup into a dependent class,
1452 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001453 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001454 // template instantiation time (at which point all bases will be available)
1455 // or we have to fail.
1456 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1457 LookupRec->hasAnyDependentBases()) {
1458 R.setNotFoundInCurrentInstantiation();
1459 return false;
1460 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001461
Douglas Gregor7176fff2009-01-15 00:26:24 +00001462 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001463 CXXBasePaths Paths;
1464 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001465
1466 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001467 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001468 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001469 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001470 case LookupOrdinaryName:
1471 case LookupMemberName:
1472 case LookupRedeclarationWithLinkage:
1473 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1474 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001475
Douglas Gregora8f32e02009-10-06 17:59:45 +00001476 case LookupTagName:
1477 BaseCallback = &CXXRecordDecl::FindTagMember;
1478 break;
John McCall9f54ad42009-12-10 09:41:52 +00001479
Douglas Gregor8071e422010-08-15 06:18:01 +00001480 case LookupAnyName:
1481 BaseCallback = &LookupAnyMember;
1482 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001483
John McCall9f54ad42009-12-10 09:41:52 +00001484 case LookupUsingDeclName:
1485 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001486
Douglas Gregora8f32e02009-10-06 17:59:45 +00001487 case LookupOperatorName:
1488 case LookupNamespaceName:
1489 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001490 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001491 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001492 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001493
Douglas Gregora8f32e02009-10-06 17:59:45 +00001494 case LookupNestedNameSpecifierName:
1495 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1496 break;
1497 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001498
John McCalla24dc2e2009-11-17 02:14:36 +00001499 if (!LookupRec->lookupInBases(BaseCallback,
1500 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001501 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001502
John McCall92f88312010-01-23 00:46:32 +00001503 R.setNamingClass(LookupRec);
1504
Douglas Gregor7176fff2009-01-15 00:26:24 +00001505 // C++ [class.member.lookup]p2:
1506 // [...] If the resulting set of declarations are not all from
1507 // sub-objects of the same type, or the set has a nonstatic member
1508 // and includes members from distinct sub-objects, there is an
1509 // ambiguity and the program is ill-formed. Otherwise that set is
1510 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001511 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001512 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001513 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001514
Douglas Gregora8f32e02009-10-06 17:59:45 +00001515 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001516 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001517 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001518
John McCall46460a62010-01-20 21:53:11 +00001519 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1520 // across all paths.
1521 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001522
Douglas Gregor7176fff2009-01-15 00:26:24 +00001523 // Determine whether we're looking at a distinct sub-object or not.
1524 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001525 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001526 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1527 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001528 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001529 }
1530
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001531 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001532 != Context.getCanonicalType(PathElement.Base->getType())) {
1533 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001534 // different types. If the declaration sets aren't the same, this
1535 // this lookup is ambiguous.
1536 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1537 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1538 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1539 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001540
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001541 while (FirstD != FirstPath->Decls.second &&
1542 CurrentD != Path->Decls.second) {
1543 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1544 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1545 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001547 ++FirstD;
1548 ++CurrentD;
1549 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001550
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001551 if (FirstD == FirstPath->Decls.second &&
1552 CurrentD == Path->Decls.second)
1553 continue;
1554 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001555
John McCallf36e02d2009-10-09 21:13:30 +00001556 R.setAmbiguousBaseSubobjectTypes(Paths);
1557 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001558 }
1559
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001560 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001561 // We have a different subobject of the same type.
1562
1563 // C++ [class.member.lookup]p5:
1564 // A static member, a nested type or an enumerator defined in
1565 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001566 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001567 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001568 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001569
Douglas Gregor7176fff2009-01-15 00:26:24 +00001570 // We have found a nonstatic member name in multiple, distinct
1571 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001572 R.setAmbiguousBaseSubobjects(Paths);
1573 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001574 }
1575 }
1576
1577 // Lookup in a base class succeeded; return these results.
1578
John McCallf36e02d2009-10-09 21:13:30 +00001579 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001580 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1581 NamedDecl *D = *I;
1582 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1583 D->getAccess());
1584 R.addDecl(D, AS);
1585 }
John McCallf36e02d2009-10-09 21:13:30 +00001586 R.resolveKind();
1587 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001588}
1589
1590/// @brief Performs name lookup for a name that was parsed in the
1591/// source code, and may contain a C++ scope specifier.
1592///
1593/// This routine is a convenience routine meant to be called from
1594/// contexts that receive a name and an optional C++ scope specifier
1595/// (e.g., "N::M::x"). It will then perform either qualified or
1596/// unqualified name lookup (with LookupQualifiedName or LookupName,
1597/// respectively) on the given name and return those results.
1598///
1599/// @param S The scope from which unqualified name lookup will
1600/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001601///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001602/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001603///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001604/// @param EnteringContext Indicates whether we are going to enter the
1605/// context of the scope-specifier SS (if present).
1606///
John McCallf36e02d2009-10-09 21:13:30 +00001607/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001608bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001609 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001610 if (SS && SS->isInvalid()) {
1611 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001612 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001613 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001614 }
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Douglas Gregor495c35d2009-08-25 22:51:20 +00001616 if (SS && SS->isSet()) {
1617 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001618 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001619 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001620 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001621 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001622
John McCalla24dc2e2009-11-17 02:14:36 +00001623 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001624 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001625 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001626
Douglas Gregor495c35d2009-08-25 22:51:20 +00001627 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001628 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001629 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001630 R.setNotFoundInCurrentInstantiation();
1631 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001632 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001633 }
1634
Mike Stump1eb44332009-09-09 15:08:12 +00001635 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001636 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001637}
1638
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001639
James Dennett16ae9de2012-06-22 10:16:05 +00001640/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001641/// from name lookup.
1642///
James Dennett16ae9de2012-06-22 10:16:05 +00001643/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump1eb44332009-09-09 15:08:12 +00001644///
James Dennett16ae9de2012-06-22 10:16:05 +00001645/// \returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001646bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001647 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1648
John McCalla24dc2e2009-11-17 02:14:36 +00001649 DeclarationName Name = Result.getLookupName();
1650 SourceLocation NameLoc = Result.getNameLoc();
1651 SourceRange LookupRange = Result.getContextRange();
1652
John McCall6e247262009-10-10 05:48:19 +00001653 switch (Result.getAmbiguityKind()) {
1654 case LookupResult::AmbiguousBaseSubobjects: {
1655 CXXBasePaths *Paths = Result.getBasePaths();
1656 QualType SubobjectType = Paths->front().back().Base->getType();
1657 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1658 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1659 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001660
John McCall6e247262009-10-10 05:48:19 +00001661 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1662 while (isa<CXXMethodDecl>(*Found) &&
1663 cast<CXXMethodDecl>(*Found)->isStatic())
1664 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001665
John McCall6e247262009-10-10 05:48:19 +00001666 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001667
John McCall6e247262009-10-10 05:48:19 +00001668 return true;
1669 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001670
John McCall6e247262009-10-10 05:48:19 +00001671 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001672 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1673 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001674
John McCall6e247262009-10-10 05:48:19 +00001675 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001676 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001677 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1678 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001679 Path != PathEnd; ++Path) {
1680 Decl *D = *Path->Decls.first;
1681 if (DeclsPrinted.insert(D).second)
1682 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1683 }
1684
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001685 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001686 }
1687
John McCall6e247262009-10-10 05:48:19 +00001688 case LookupResult::AmbiguousTagHiding: {
1689 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001690
John McCall6e247262009-10-10 05:48:19 +00001691 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1692
1693 LookupResult::iterator DI, DE = Result.end();
1694 for (DI = Result.begin(); DI != DE; ++DI)
1695 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1696 TagDecls.insert(TD);
1697 Diag(TD->getLocation(), diag::note_hidden_tag);
1698 }
1699
1700 for (DI = Result.begin(); DI != DE; ++DI)
1701 if (!isa<TagDecl>(*DI))
1702 Diag((*DI)->getLocation(), diag::note_hiding_object);
1703
1704 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001705 LookupResult::Filter F = Result.makeFilter();
1706 while (F.hasNext()) {
1707 if (TagDecls.count(F.next()))
1708 F.erase();
1709 }
1710 F.done();
John McCall6e247262009-10-10 05:48:19 +00001711
1712 return true;
1713 }
1714
1715 case LookupResult::AmbiguousReference: {
1716 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001717
John McCall6e247262009-10-10 05:48:19 +00001718 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1719 for (; DI != DE; ++DI)
1720 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001721
John McCall6e247262009-10-10 05:48:19 +00001722 return true;
1723 }
1724 }
1725
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001726 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001727}
Douglas Gregorfa047642009-02-04 00:32:51 +00001728
John McCallc7e04da2010-05-28 18:45:08 +00001729namespace {
1730 struct AssociatedLookup {
1731 AssociatedLookup(Sema &S,
1732 Sema::AssociatedNamespaceSet &Namespaces,
1733 Sema::AssociatedClassSet &Classes)
1734 : S(S), Namespaces(Namespaces), Classes(Classes) {
1735 }
1736
1737 Sema &S;
1738 Sema::AssociatedNamespaceSet &Namespaces;
1739 Sema::AssociatedClassSet &Classes;
1740 };
1741}
1742
Mike Stump1eb44332009-09-09 15:08:12 +00001743static void
John McCallc7e04da2010-05-28 18:45:08 +00001744addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001745
Douglas Gregor54022952010-04-30 07:08:38 +00001746static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1747 DeclContext *Ctx) {
1748 // Add the associated namespace for this class.
1749
1750 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1751 // be a locally scoped record.
1752
Sebastian Redl410c4f22010-08-31 20:53:31 +00001753 // We skip out of inline namespaces. The innermost non-inline namespace
1754 // contains all names of all its nested inline namespaces anyway, so we can
1755 // replace the entire inline namespace tree with its root.
1756 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1757 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001758 Ctx = Ctx->getParent();
1759
John McCall6ff07852009-08-07 22:18:02 +00001760 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001761 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001762}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001763
Mike Stump1eb44332009-09-09 15:08:12 +00001764// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001765// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001766static void
John McCallc7e04da2010-05-28 18:45:08 +00001767addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1768 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001769 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001771 switch (Arg.getKind()) {
1772 case TemplateArgument::Null:
1773 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Douglas Gregor69be8d62009-07-08 07:51:57 +00001775 case TemplateArgument::Type:
1776 // [...] the namespaces and classes associated with the types of the
1777 // template arguments provided for template type parameters (excluding
1778 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001779 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001780 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001781
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001783 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001784 // [...] the namespaces in which any template template arguments are
1785 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001786 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001787 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001788 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001789 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001790 DeclContext *Ctx = ClassTemplate->getDeclContext();
1791 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001792 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001793 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001794 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001795 }
1796 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001797 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798
Douglas Gregor788cd062009-11-11 01:00:40 +00001799 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001800 case TemplateArgument::Integral:
1801 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001802 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001803 // associated namespaces. ]
1804 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Douglas Gregor69be8d62009-07-08 07:51:57 +00001806 case TemplateArgument::Pack:
1807 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1808 PEnd = Arg.pack_end();
1809 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001810 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001811 break;
1812 }
1813}
1814
Douglas Gregorfa047642009-02-04 00:32:51 +00001815// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001816// argument-dependent lookup with an argument of class type
1817// (C++ [basic.lookup.koenig]p2).
1818static void
John McCallc7e04da2010-05-28 18:45:08 +00001819addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1820 CXXRecordDecl *Class) {
1821
1822 // Just silently ignore anything whose name is __va_list_tag.
1823 if (Class->getDeclName() == Result.S.VAListTagName)
1824 return;
1825
Douglas Gregorfa047642009-02-04 00:32:51 +00001826 // C++ [basic.lookup.koenig]p2:
1827 // [...]
1828 // -- If T is a class type (including unions), its associated
1829 // classes are: the class itself; the class of which it is a
1830 // member, if any; and its direct and indirect base
1831 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001832 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001833
1834 // Add the class of which it is a member, if any.
1835 DeclContext *Ctx = Class->getDeclContext();
1836 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001837 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001838 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001839 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Douglas Gregorfa047642009-02-04 00:32:51 +00001841 // Add the class itself. If we've already seen this class, we don't
1842 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001843 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001844 return;
1845
Mike Stump1eb44332009-09-09 15:08:12 +00001846 // -- If T is a template-id, its associated namespaces and classes are
1847 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001848 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001849 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001850 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001851 // namespaces in which any template template arguments are defined; and
1852 // the classes in which any member templates used as template template
1853 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001854 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001855 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001856 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1857 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1858 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001859 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001860 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001861 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor69be8d62009-07-08 07:51:57 +00001863 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1864 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001865 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001866 }
Mike Stump1eb44332009-09-09 15:08:12 +00001867
John McCall86ff3082010-02-04 22:26:26 +00001868 // Only recurse into base classes for complete types.
1869 if (!Class->hasDefinition()) {
1870 // FIXME: we might need to instantiate templates here
1871 return;
1872 }
1873
Douglas Gregorfa047642009-02-04 00:32:51 +00001874 // Add direct and indirect base classes along with their associated
1875 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001876 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001877 Bases.push_back(Class);
1878 while (!Bases.empty()) {
1879 // Pop this class off the stack.
1880 Class = Bases.back();
1881 Bases.pop_back();
1882
1883 // Visit the base classes.
1884 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1885 BaseEnd = Class->bases_end();
1886 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001887 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001888 // In dependent contexts, we do ADL twice, and the first time around,
1889 // the base type might be a dependent TemplateSpecializationType, or a
1890 // TemplateTypeParmType. If that happens, simply ignore it.
1891 // FIXME: If we want to support export, we probably need to add the
1892 // namespace of the template in a TemplateSpecializationType, or even
1893 // the classes and namespaces of known non-dependent arguments.
1894 if (!BaseType)
1895 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001896 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001897 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001898 // Find the associated namespace for this base class.
1899 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001900 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001901
1902 // Make sure we visit the bases of this base class.
1903 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1904 Bases.push_back(BaseDecl);
1905 }
1906 }
1907 }
1908}
1909
1910// \brief Add the associated classes and namespaces for
1911// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001912// (C++ [basic.lookup.koenig]p2).
1913static void
John McCallc7e04da2010-05-28 18:45:08 +00001914addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001915 // C++ [basic.lookup.koenig]p2:
1916 //
1917 // For each argument type T in the function call, there is a set
1918 // of zero or more associated namespaces and a set of zero or more
1919 // associated classes to be considered. The sets of namespaces and
1920 // classes is determined entirely by the types of the function
1921 // arguments (and the namespace of any template template
1922 // argument). Typedef names and using-declarations used to specify
1923 // the types do not contribute to this set. The sets of namespaces
1924 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001925
Chris Lattner5f9e2722011-07-23 10:55:15 +00001926 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001927 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1928
Douglas Gregorfa047642009-02-04 00:32:51 +00001929 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001930 switch (T->getTypeClass()) {
1931
1932#define TYPE(Class, Base)
1933#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1934#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1935#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1936#define ABSTRACT_TYPE(Class, Base)
1937#include "clang/AST/TypeNodes.def"
1938 // T is canonical. We can also ignore dependent types because
1939 // we don't need to do ADL at the definition point, but if we
1940 // wanted to implement template export (or if we find some other
1941 // use for associated classes and namespaces...) this would be
1942 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001943 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001944
John McCallfa4edcf2010-05-28 06:08:54 +00001945 // -- If T is a pointer to U or an array of U, its associated
1946 // namespaces and classes are those associated with U.
1947 case Type::Pointer:
1948 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1949 continue;
1950 case Type::ConstantArray:
1951 case Type::IncompleteArray:
1952 case Type::VariableArray:
1953 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1954 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001955
John McCallfa4edcf2010-05-28 06:08:54 +00001956 // -- If T is a fundamental type, its associated sets of
1957 // namespaces and classes are both empty.
1958 case Type::Builtin:
1959 break;
1960
1961 // -- If T is a class type (including unions), its associated
1962 // classes are: the class itself; the class of which it is a
1963 // member, if any; and its direct and indirect base
1964 // classes. Its associated namespaces are the namespaces in
1965 // which its associated classes are defined.
1966 case Type::Record: {
1967 CXXRecordDecl *Class
1968 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001969 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001970 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001971 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001972
John McCallfa4edcf2010-05-28 06:08:54 +00001973 // -- If T is an enumeration type, its associated namespace is
1974 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001975 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001976 // it has no associated class.
1977 case Type::Enum: {
1978 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001979
John McCallfa4edcf2010-05-28 06:08:54 +00001980 DeclContext *Ctx = Enum->getDeclContext();
1981 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001982 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001983
John McCallfa4edcf2010-05-28 06:08:54 +00001984 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001985 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001986
John McCallfa4edcf2010-05-28 06:08:54 +00001987 break;
1988 }
1989
1990 // -- If T is a function type, its associated namespaces and
1991 // classes are those associated with the function parameter
1992 // types and those associated with the return type.
1993 case Type::FunctionProto: {
1994 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1995 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1996 ArgEnd = Proto->arg_type_end();
1997 Arg != ArgEnd; ++Arg)
1998 Queue.push_back(Arg->getTypePtr());
1999 // fallthrough
2000 }
2001 case Type::FunctionNoProto: {
2002 const FunctionType *FnType = cast<FunctionType>(T);
2003 T = FnType->getResultType().getTypePtr();
2004 continue;
2005 }
2006
2007 // -- If T is a pointer to a member function of a class X, its
2008 // associated namespaces and classes are those associated
2009 // with the function parameter types and return type,
2010 // together with those associated with X.
2011 //
2012 // -- If T is a pointer to a data member of class X, its
2013 // associated namespaces and classes are those associated
2014 // with the member type together with those associated with
2015 // X.
2016 case Type::MemberPointer: {
2017 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2018
2019 // Queue up the class type into which this points.
2020 Queue.push_back(MemberPtr->getClass());
2021
2022 // And directly continue with the pointee type.
2023 T = MemberPtr->getPointeeType().getTypePtr();
2024 continue;
2025 }
2026
2027 // As an extension, treat this like a normal pointer.
2028 case Type::BlockPointer:
2029 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2030 continue;
2031
2032 // References aren't covered by the standard, but that's such an
2033 // obvious defect that we cover them anyway.
2034 case Type::LValueReference:
2035 case Type::RValueReference:
2036 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2037 continue;
2038
2039 // These are fundamental types.
2040 case Type::Vector:
2041 case Type::ExtVector:
2042 case Type::Complex:
2043 break;
2044
Douglas Gregorf25760e2011-04-12 01:02:45 +00002045 // If T is an Objective-C object or interface type, or a pointer to an
2046 // object or interface type, the associated namespace is the global
2047 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002048 case Type::ObjCObject:
2049 case Type::ObjCInterface:
2050 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002051 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002052 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002053
2054 // Atomic types are just wrappers; use the associations of the
2055 // contained type.
2056 case Type::Atomic:
2057 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2058 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002059 }
2060
2061 if (Queue.empty()) break;
2062 T = Queue.back();
2063 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002064 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002065}
2066
2067/// \brief Find the associated classes and namespaces for
2068/// argument-dependent lookup for a call with the given set of
2069/// arguments.
2070///
2071/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002072/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002073/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002074void
Ahmed Charles13a140c2012-02-25 11:00:22 +00002075Sema::FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002076 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002077 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002078 AssociatedNamespaces.clear();
2079 AssociatedClasses.clear();
2080
John McCallc7e04da2010-05-28 18:45:08 +00002081 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2082
Douglas Gregorfa047642009-02-04 00:32:51 +00002083 // C++ [basic.lookup.koenig]p2:
2084 // For each argument type T in the function call, there is a set
2085 // of zero or more associated namespaces and a set of zero or more
2086 // associated classes to be considered. The sets of namespaces and
2087 // classes is determined entirely by the types of the function
2088 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002089 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002090 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002091 Expr *Arg = Args[ArgIdx];
2092
2093 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002094 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002095 continue;
2096 }
2097
2098 // [...] In addition, if the argument is the name or address of a
2099 // set of overloaded functions and/or function templates, its
2100 // associated classes and namespaces are the union of those
2101 // associated with each of the members of the set: the namespace
2102 // in which the function or function template is defined and the
2103 // classes and namespaces associated with its (non-dependent)
2104 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002105 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002106 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002107 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002108 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002109
John McCallc7e04da2010-05-28 18:45:08 +00002110 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2111 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002112
John McCallc7e04da2010-05-28 18:45:08 +00002113 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2114 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002115 // Look through any using declarations to find the underlying function.
2116 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002117
Chandler Carruthbd647292009-12-29 06:17:27 +00002118 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2119 if (!FDecl)
2120 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002121
2122 // Add the classes and namespaces associated with the parameter
2123 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002124 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002125 }
2126 }
2127}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002128
2129/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2130/// an acceptable non-member overloaded operator for a call whose
2131/// arguments have types T1 (and, if non-empty, T2). This routine
2132/// implements the check in C++ [over.match.oper]p3b2 concerning
2133/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002134static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002135IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2136 QualType T1, QualType T2,
2137 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002138 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2139 return true;
2140
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002141 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2142 return true;
2143
John McCall183700f2009-09-21 23:43:11 +00002144 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002145 if (Proto->getNumArgs() < 1)
2146 return false;
2147
2148 if (T1->isEnumeralType()) {
2149 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002150 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002151 return true;
2152 }
2153
2154 if (Proto->getNumArgs() < 2)
2155 return false;
2156
2157 if (!T2.isNull() && T2->isEnumeralType()) {
2158 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002159 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002160 return true;
2161 }
2162
2163 return false;
2164}
2165
John McCall7d384dd2009-11-18 07:57:50 +00002166NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002167 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002168 LookupNameKind NameKind,
2169 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002170 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002171 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002172 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002173}
2174
Douglas Gregor6e378de2009-04-23 23:18:26 +00002175/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002176ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002177 SourceLocation IdLoc,
2178 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002179 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002180 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002181 return cast_or_null<ObjCProtocolDecl>(D);
2182}
2183
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002184void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002185 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002186 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002187 // C++ [over.match.oper]p3:
2188 // -- The set of non-member candidates is the result of the
2189 // unqualified lookup of operator@ in the context of the
2190 // expression according to the usual rules for name lookup in
2191 // unqualified function calls (3.4.2) except that all member
2192 // functions are ignored. However, if no operand has a class
2193 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002194 // that have a first parameter of type T1 or "reference to
2195 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002196 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002197 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002198 // when T2 is an enumeration type, are candidate functions.
2199 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002200 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2201 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002203 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2204
John McCallf36e02d2009-10-09 21:13:30 +00002205 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002206 return;
2207
2208 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2209 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002210 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2211 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002212 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002213 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002214 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002215 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002216 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002217 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002218 // later?
2219 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002220 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002221 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002222 }
2223}
2224
Sean Huntc39b6bc2011-06-24 02:11:39 +00002225Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002226 CXXSpecialMember SM,
2227 bool ConstArg,
2228 bool VolatileArg,
2229 bool RValueThis,
2230 bool ConstThis,
2231 bool VolatileThis) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002232 RD = RD->getDefinition();
2233 assert((RD && !RD->isBeingDefined()) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002234 "doing special member lookup into record that isn't fully complete");
2235 if (RValueThis || ConstThis || VolatileThis)
2236 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2237 "constructors and destructors always have unqualified lvalue this");
2238 if (ConstArg || VolatileArg)
2239 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2240 "parameter-less special members can't have qualified arguments");
2241
2242 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002243 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002244 ID.AddInteger(SM);
2245 ID.AddInteger(ConstArg);
2246 ID.AddInteger(VolatileArg);
2247 ID.AddInteger(RValueThis);
2248 ID.AddInteger(ConstThis);
2249 ID.AddInteger(VolatileThis);
2250
2251 void *InsertPoint;
2252 SpecialMemberOverloadResult *Result =
2253 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2254
2255 // This was already cached
2256 if (Result)
2257 return Result;
2258
Sean Hunt30543582011-06-07 00:11:58 +00002259 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2260 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002261 SpecialMemberCache.InsertNode(Result, InsertPoint);
2262
2263 if (SM == CXXDestructor) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002264 if (!RD->hasDeclaredDestructor())
2265 DeclareImplicitDestructor(RD);
2266 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002267 assert(DD && "record without a destructor");
2268 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002269 Result->setKind(DD->isDeleted() ?
2270 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002271 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002272 return Result;
2273 }
2274
Sean Huntb320e0c2011-06-10 03:50:41 +00002275 // Prepare for overload resolution. Here we construct a synthetic argument
2276 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002277 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002278 DeclarationName Name;
2279 Expr *Arg = 0;
2280 unsigned NumArgs;
2281
Richard Smith704c8f72012-04-20 18:46:14 +00002282 QualType ArgType = CanTy;
2283 ExprValueKind VK = VK_LValue;
2284
Sean Huntb320e0c2011-06-10 03:50:41 +00002285 if (SM == CXXDefaultConstructor) {
2286 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2287 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002288 if (RD->needsImplicitDefaultConstructor())
2289 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002290 } else {
2291 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2292 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002293 if (!RD->hasDeclaredCopyConstructor())
2294 DeclareImplicitCopyConstructor(RD);
David Blaikie4e4d0842012-03-11 07:00:24 +00002295 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002296 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002297 } else {
2298 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002299 if (!RD->hasDeclaredCopyAssignment())
2300 DeclareImplicitCopyAssignment(RD);
David Blaikie4e4d0842012-03-11 07:00:24 +00002301 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002302 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002303 }
2304
Sean Huntb320e0c2011-06-10 03:50:41 +00002305 if (ConstArg)
2306 ArgType.addConst();
2307 if (VolatileArg)
2308 ArgType.addVolatile();
2309
2310 // This isn't /really/ specified by the standard, but it's implied
2311 // we should be working from an RValue in the case of move to ensure
2312 // that we prefer to bind to rvalue references, and an LValue in the
2313 // case of copy to ensure we don't bind to rvalue references.
2314 // Possibly an XValue is actually correct in the case of move, but
2315 // there is no semantic difference for class types in this restricted
2316 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002317 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002318 VK = VK_LValue;
2319 else
2320 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002321 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002322
Richard Smith704c8f72012-04-20 18:46:14 +00002323 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2324
2325 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002326 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002327 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002328 }
2329
2330 // Create the object argument
2331 QualType ThisTy = CanTy;
2332 if (ConstThis)
2333 ThisTy.addConst();
2334 if (VolatileThis)
2335 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002336 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002337 OpaqueValueExpr(SourceLocation(), ThisTy,
2338 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002339
2340 // Now we perform lookup on the name we computed earlier and do overload
2341 // resolution. Lookup is only performed directly into the class since there
2342 // will always be a (possibly implicit) declaration to shadow any others.
2343 OverloadCandidateSet OCS((SourceLocation()));
2344 DeclContext::lookup_iterator I, E;
Sean Huntb320e0c2011-06-10 03:50:41 +00002345
Sean Huntc39b6bc2011-06-24 02:11:39 +00002346 llvm::tie(I, E) = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002347 assert((I != E) &&
2348 "lookup for a constructor or assignment operator was empty");
2349 for ( ; I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002350 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002351
Sean Huntc39b6bc2011-06-24 02:11:39 +00002352 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002353 continue;
2354
Sean Huntc39b6bc2011-06-24 02:11:39 +00002355 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2356 // FIXME: [namespace.udecl]p15 says that we should only consider a
2357 // using declaration here if it does not match a declaration in the
2358 // derived class. We do not implement this correctly in other cases
2359 // either.
2360 Cand = U->getTargetDecl();
2361
2362 if (Cand->isInvalidDecl())
2363 continue;
2364 }
2365
2366 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002367 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002368 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002369 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2370 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002371 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002372 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2373 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002374 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002375 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002376 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2377 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002378 RD, 0, ThisTy, Classification,
2379 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002380 OCS, true);
2381 else
2382 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002383 0, llvm::makeArrayRef(&Arg, NumArgs),
2384 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002385 } else {
2386 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002387 }
2388 }
2389
2390 OverloadCandidateSet::iterator Best;
2391 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2392 case OR_Success:
2393 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002394 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002395 break;
2396
2397 case OR_Deleted:
2398 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002399 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002400 break;
2401
2402 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002403 Result->setMethod(0);
2404 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2405 break;
2406
Sean Huntb320e0c2011-06-10 03:50:41 +00002407 case OR_No_Viable_Function:
2408 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002409 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002410 break;
2411 }
2412
2413 return Result;
2414}
2415
2416/// \brief Look up the default constructor for the given class.
2417CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002418 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002419 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2420 false, false);
2421
2422 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002423}
2424
Sean Hunt661c67a2011-06-21 23:42:56 +00002425/// \brief Look up the copying constructor for the given class.
2426CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002427 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002428 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2429 "non-const, non-volatile qualifiers for copy ctor arg");
2430 SpecialMemberOverloadResult *Result =
2431 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2432 Quals & Qualifiers::Volatile, false, false, false);
2433
Sean Huntc530d172011-06-10 04:44:37 +00002434 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2435}
2436
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002437/// \brief Look up the moving constructor for the given class.
2438CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2439 SpecialMemberOverloadResult *Result =
2440 LookupSpecialMember(Class, CXXMoveConstructor, false,
2441 false, false, false, false);
2442
2443 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2444}
2445
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002446/// \brief Look up the constructors for the given class.
2447DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002448 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002449 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002450 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002451 DeclareImplicitDefaultConstructor(Class);
2452 if (!Class->hasDeclaredCopyConstructor())
2453 DeclareImplicitCopyConstructor(Class);
David Blaikie4e4d0842012-03-11 07:00:24 +00002454 if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002455 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002456 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002457
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002458 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2459 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2460 return Class->lookup(Name);
2461}
2462
Sean Hunt661c67a2011-06-21 23:42:56 +00002463/// \brief Look up the copying assignment operator for the given class.
2464CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2465 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002466 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002467 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2468 "non-const, non-volatile qualifiers for copy assignment arg");
2469 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2470 "non-const, non-volatile qualifiers for copy assignment this");
2471 SpecialMemberOverloadResult *Result =
2472 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2473 Quals & Qualifiers::Volatile, RValueThis,
2474 ThisQuals & Qualifiers::Const,
2475 ThisQuals & Qualifiers::Volatile);
2476
Sean Hunt661c67a2011-06-21 23:42:56 +00002477 return Result->getMethod();
2478}
2479
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002480/// \brief Look up the moving assignment operator for the given class.
2481CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2482 bool RValueThis,
2483 unsigned ThisQuals) {
2484 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2485 "non-const, non-volatile qualifiers for copy assignment this");
2486 SpecialMemberOverloadResult *Result =
2487 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2488 ThisQuals & Qualifiers::Const,
2489 ThisQuals & Qualifiers::Volatile);
2490
2491 return Result->getMethod();
2492}
2493
Douglas Gregordb89f282010-07-01 22:47:18 +00002494/// \brief Look for the destructor of the given class.
2495///
Sean Huntc5c9b532011-06-03 21:10:40 +00002496/// During semantic analysis, this routine should be used in lieu of
2497/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002498///
2499/// \returns The destructor for this class.
2500CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002501 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2502 false, false, false,
2503 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002504}
2505
Richard Smith36f5cfe2012-03-09 08:00:36 +00002506/// LookupLiteralOperator - Determine which literal operator should be used for
2507/// a user-defined literal, per C++11 [lex.ext].
2508///
2509/// Normal overload resolution is not used to select which literal operator to
2510/// call for a user-defined literal. Look up the provided literal operator name,
2511/// and filter the results to the appropriate set for the given argument types.
2512Sema::LiteralOperatorLookupResult
2513Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2514 ArrayRef<QualType> ArgTys,
2515 bool AllowRawAndTemplate) {
2516 LookupName(R, S);
2517 assert(R.getResultKind() != LookupResult::Ambiguous &&
2518 "literal operator lookup can't be ambiguous");
2519
2520 // Filter the lookup results appropriately.
2521 LookupResult::Filter F = R.makeFilter();
2522
2523 bool FoundTemplate = false;
2524 bool FoundRaw = false;
2525 bool FoundExactMatch = false;
2526
2527 while (F.hasNext()) {
2528 Decl *D = F.next();
2529 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2530 D = USD->getTargetDecl();
2531
2532 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2533 bool IsRaw = false;
2534 bool IsExactMatch = false;
2535
2536 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2537 if (FD->getNumParams() == 1 &&
2538 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2539 IsRaw = true;
2540 else {
2541 IsExactMatch = true;
2542 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2543 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2544 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2545 IsExactMatch = false;
2546 break;
2547 }
2548 }
2549 }
2550 }
2551
2552 if (IsExactMatch) {
2553 FoundExactMatch = true;
2554 AllowRawAndTemplate = false;
2555 if (FoundRaw || FoundTemplate) {
2556 // Go through again and remove the raw and template decls we've
2557 // already found.
2558 F.restart();
2559 FoundRaw = FoundTemplate = false;
2560 }
2561 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2562 FoundTemplate |= IsTemplate;
2563 FoundRaw |= IsRaw;
2564 } else {
2565 F.erase();
2566 }
2567 }
2568
2569 F.done();
2570
2571 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2572 // parameter type, that is used in preference to a raw literal operator
2573 // or literal operator template.
2574 if (FoundExactMatch)
2575 return LOLR_Cooked;
2576
2577 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2578 // operator template, but not both.
2579 if (FoundRaw && FoundTemplate) {
2580 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2581 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2582 Decl *D = *I;
2583 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2584 D = USD->getTargetDecl();
2585 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2586 D = FunTmpl->getTemplatedDecl();
2587 NoteOverloadCandidate(cast<FunctionDecl>(D));
2588 }
2589 return LOLR_Error;
2590 }
2591
2592 if (FoundRaw)
2593 return LOLR_Raw;
2594
2595 if (FoundTemplate)
2596 return LOLR_Template;
2597
2598 // Didn't find anything we could use.
2599 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2600 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2601 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2602 return LOLR_Error;
2603}
2604
John McCall7edb5fd2010-01-26 07:16:45 +00002605void ADLResult::insert(NamedDecl *New) {
2606 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2607
2608 // If we haven't yet seen a decl for this key, or the last decl
2609 // was exactly this one, we're done.
2610 if (Old == 0 || Old == New) {
2611 Old = New;
2612 return;
2613 }
2614
2615 // Otherwise, decide which is a more recent redeclaration.
2616 FunctionDecl *OldFD, *NewFD;
2617 if (isa<FunctionTemplateDecl>(New)) {
2618 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2619 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2620 } else {
2621 OldFD = cast<FunctionDecl>(Old);
2622 NewFD = cast<FunctionDecl>(New);
2623 }
2624
2625 FunctionDecl *Cursor = NewFD;
2626 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002627 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002628
2629 // If we got to the end without finding OldFD, OldFD is the newer
2630 // declaration; leave things as they are.
2631 if (!Cursor) return;
2632
2633 // If we do find OldFD, then NewFD is newer.
2634 if (Cursor == OldFD) break;
2635
2636 // Otherwise, keep looking.
2637 }
2638
2639 Old = New;
2640}
2641
Sebastian Redl644be852009-10-23 19:23:15 +00002642void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00002643 SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002644 llvm::ArrayRef<Expr *> Args,
Richard Smithad762fc2011-04-14 22:09:26 +00002645 ADLResult &Result,
2646 bool StdNamespaceIsAssociated) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002647 // Find all of the associated namespaces and classes based on the
2648 // arguments we have.
2649 AssociatedNamespaceSet AssociatedNamespaces;
2650 AssociatedClassSet AssociatedClasses;
Ahmed Charles13a140c2012-02-25 11:00:22 +00002651 FindAssociatedClassesAndNamespaces(Args,
John McCall6ff07852009-08-07 22:18:02 +00002652 AssociatedNamespaces,
2653 AssociatedClasses);
Richard Smithad762fc2011-04-14 22:09:26 +00002654 if (StdNamespaceIsAssociated && StdNamespace)
2655 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002656
Sebastian Redl644be852009-10-23 19:23:15 +00002657 QualType T1, T2;
2658 if (Operator) {
2659 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002660 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002661 T2 = Args[1]->getType();
2662 }
2663
Richard Smithf5cd5cc2012-02-25 06:24:24 +00002664 // Try to complete all associated classes, in case they contain a
2665 // declaration of a friend function.
2666 for (AssociatedClassSet::iterator C = AssociatedClasses.begin(),
2667 CEnd = AssociatedClasses.end();
2668 C != CEnd; ++C)
2669 RequireCompleteType(Loc, Context.getRecordType(*C), 0);
2670
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002671 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002672 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2673 // and let Y be the lookup set produced by argument dependent
2674 // lookup (defined as follows). If X contains [...] then Y is
2675 // empty. Otherwise Y is the set of declarations found in the
2676 // namespaces associated with the argument types as described
2677 // below. The set of declarations found by the lookup of the name
2678 // is the union of X and Y.
2679 //
2680 // Here, we compute Y and add its members to the overloaded
2681 // candidate set.
2682 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002683 NSEnd = AssociatedNamespaces.end();
2684 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002685 // When considering an associated namespace, the lookup is the
2686 // same as the lookup performed when the associated namespace is
2687 // used as a qualifier (3.4.3.2) except that:
2688 //
2689 // -- Any using-directives in the associated namespace are
2690 // ignored.
2691 //
John McCall6ff07852009-08-07 22:18:02 +00002692 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002693 // associated classes are visible within their respective
2694 // namespaces even if they are not visible during an ordinary
2695 // lookup (11.4).
2696 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002697 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002698 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002699 // If the only declaration here is an ordinary friend, consider
2700 // it only if it was declared in an associated classes.
2701 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002702 DeclContext *LexDC = D->getLexicalDeclContext();
2703 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2704 continue;
2705 }
Mike Stump1eb44332009-09-09 15:08:12 +00002706
John McCalla113e722010-01-26 06:04:06 +00002707 if (isa<UsingShadowDecl>(D))
2708 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002709
John McCalla113e722010-01-26 06:04:06 +00002710 if (isa<FunctionDecl>(D)) {
2711 if (Operator &&
2712 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2713 T1, T2, Context))
2714 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002715 } else if (!isa<FunctionTemplateDecl>(D))
2716 continue;
2717
2718 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002719 }
2720 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002721}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002722
2723//----------------------------------------------------------------------------
2724// Search for all visible declarations.
2725//----------------------------------------------------------------------------
2726VisibleDeclConsumer::~VisibleDeclConsumer() { }
2727
2728namespace {
2729
2730class ShadowContextRAII;
2731
2732class VisibleDeclsRecord {
2733public:
2734 /// \brief An entry in the shadow map, which is optimized to store a
2735 /// single declaration (the common case) but can also store a list
2736 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002737 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002738
2739private:
2740 /// \brief A mapping from declaration names to the declarations that have
2741 /// this name within a particular scope.
2742 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2743
2744 /// \brief A list of shadow maps, which is used to model name hiding.
2745 std::list<ShadowMap> ShadowMaps;
2746
2747 /// \brief The declaration contexts we have already visited.
2748 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2749
2750 friend class ShadowContextRAII;
2751
2752public:
2753 /// \brief Determine whether we have already visited this context
2754 /// (and, if not, note that we are going to visit that context now).
2755 bool visitedContext(DeclContext *Ctx) {
2756 return !VisitedContexts.insert(Ctx);
2757 }
2758
Douglas Gregor8071e422010-08-15 06:18:01 +00002759 bool alreadyVisitedContext(DeclContext *Ctx) {
2760 return VisitedContexts.count(Ctx);
2761 }
2762
Douglas Gregor546be3c2009-12-30 17:04:44 +00002763 /// \brief Determine whether the given declaration is hidden in the
2764 /// current scope.
2765 ///
2766 /// \returns the declaration that hides the given declaration, or
2767 /// NULL if no such declaration exists.
2768 NamedDecl *checkHidden(NamedDecl *ND);
2769
2770 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002771 void add(NamedDecl *ND) {
2772 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2773 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002774};
2775
2776/// \brief RAII object that records when we've entered a shadow context.
2777class ShadowContextRAII {
2778 VisibleDeclsRecord &Visible;
2779
2780 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2781
2782public:
2783 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2784 Visible.ShadowMaps.push_back(ShadowMap());
2785 }
2786
2787 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002788 Visible.ShadowMaps.pop_back();
2789 }
2790};
2791
2792} // end anonymous namespace
2793
Douglas Gregor546be3c2009-12-30 17:04:44 +00002794NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002795 // Look through using declarations.
2796 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002797
Douglas Gregor546be3c2009-12-30 17:04:44 +00002798 unsigned IDNS = ND->getIdentifierNamespace();
2799 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2800 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2801 SM != SMEnd; ++SM) {
2802 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2803 if (Pos == SM->end())
2804 continue;
2805
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002806 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002807 IEnd = Pos->second.end();
2808 I != IEnd; ++I) {
2809 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002810 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002811 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002812 Decl::IDNS_ObjCProtocol)))
2813 continue;
2814
2815 // Protocols are in distinct namespaces from everything else.
2816 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2817 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2818 (*I)->getIdentifierNamespace() != IDNS)
2819 continue;
2820
Douglas Gregor0cc84042010-01-14 15:47:35 +00002821 // Functions and function templates in the same scope overload
2822 // rather than hide. FIXME: Look for hiding based on function
2823 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002824 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002825 ND->isFunctionOrFunctionTemplate() &&
2826 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002827 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002828
Douglas Gregor546be3c2009-12-30 17:04:44 +00002829 // We've found a declaration that hides this one.
2830 return *I;
2831 }
2832 }
2833
2834 return 0;
2835}
2836
2837static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2838 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002839 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002840 VisibleDeclConsumer &Consumer,
2841 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002842 if (!Ctx)
2843 return;
2844
Douglas Gregor546be3c2009-12-30 17:04:44 +00002845 // Make sure we don't visit the same context twice.
2846 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2847 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002848
Douglas Gregor4923aa22010-07-02 20:37:36 +00002849 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2850 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2851
Douglas Gregor546be3c2009-12-30 17:04:44 +00002852 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00002853 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2854 LEnd = Ctx->lookups_end();
2855 L != LEnd; ++L) {
2856 for (DeclContext::lookup_result R = *L; R.first != R.second; ++R.first) {
2857 if (NamedDecl *ND = dyn_cast<NamedDecl>(*R.first)) {
Douglas Gregor55368912011-12-14 16:03:29 +00002858 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002859 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002860 Visited.add(ND);
2861 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002862 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002863 }
2864 }
2865
2866 // Traverse using directives for qualified name lookup.
2867 if (QualifiedNameLookup) {
2868 ShadowContextRAII Shadow(Visited);
2869 DeclContext::udir_iterator I, E;
2870 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002871 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002872 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002873 }
2874 }
2875
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002876 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002877 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002878 if (!Record->hasDefinition())
2879 return;
2880
Douglas Gregor546be3c2009-12-30 17:04:44 +00002881 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2882 BEnd = Record->bases_end();
2883 B != BEnd; ++B) {
2884 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002885
Douglas Gregor546be3c2009-12-30 17:04:44 +00002886 // Don't look into dependent bases, because name lookup can't look
2887 // there anyway.
2888 if (BaseType->isDependentType())
2889 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002890
Douglas Gregor546be3c2009-12-30 17:04:44 +00002891 const RecordType *Record = BaseType->getAs<RecordType>();
2892 if (!Record)
2893 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002894
Douglas Gregor546be3c2009-12-30 17:04:44 +00002895 // FIXME: It would be nice to be able to determine whether referencing
2896 // a particular member would be ambiguous. For example, given
2897 //
2898 // struct A { int member; };
2899 // struct B { int member; };
2900 // struct C : A, B { };
2901 //
2902 // void f(C *c) { c->### }
2903 //
2904 // accessing 'member' would result in an ambiguity. However, we
2905 // could be smart enough to qualify the member with the base
2906 // class, e.g.,
2907 //
2908 // c->B::member
2909 //
2910 // or
2911 //
2912 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002913
Douglas Gregor546be3c2009-12-30 17:04:44 +00002914 // Find results in this base class (and its bases).
2915 ShadowContextRAII Shadow(Visited);
2916 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002917 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002918 }
2919 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002920
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002921 // Traverse the contexts of Objective-C classes.
2922 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2923 // Traverse categories.
2924 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2925 Category; Category = Category->getNextClassCategory()) {
2926 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002927 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002928 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002929 }
2930
2931 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002932 for (ObjCInterfaceDecl::all_protocol_iterator
2933 I = IFace->all_referenced_protocol_begin(),
2934 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002935 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002936 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002937 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002938 }
2939
2940 // Traverse the superclass.
2941 if (IFace->getSuperClass()) {
2942 ShadowContextRAII Shadow(Visited);
2943 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002944 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002945 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002946
Douglas Gregorc220a182010-04-19 18:02:19 +00002947 // If there is an implementation, traverse it. We do this to find
2948 // synthesized ivars.
2949 if (IFace->getImplementation()) {
2950 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002951 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00002952 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00002953 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002954 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2955 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2956 E = Protocol->protocol_end(); I != E; ++I) {
2957 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002958 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002959 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002960 }
2961 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2962 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2963 E = Category->protocol_end(); I != E; ++I) {
2964 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002965 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002966 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002967 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002968
Douglas Gregorc220a182010-04-19 18:02:19 +00002969 // If there is an implementation, traverse it.
2970 if (Category->getImplementation()) {
2971 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002972 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002973 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002974 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002975 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002976}
2977
2978static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2979 UnqualUsingDirectiveSet &UDirs,
2980 VisibleDeclConsumer &Consumer,
2981 VisibleDeclsRecord &Visited) {
2982 if (!S)
2983 return;
2984
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002985 if (!S->getEntity() ||
2986 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002987 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002988 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2989 // Walk through the declarations in this Scope.
2990 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2991 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002992 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00002993 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002994 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002995 Visited.add(ND);
2996 }
2997 }
2998 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002999
Douglas Gregor711be1e2010-03-15 14:33:29 +00003000 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003001 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003002 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003003 // Look into this scope's declaration context, along with any of its
3004 // parent lookup contexts (e.g., enclosing classes), up to the point
3005 // where we hit the context stored in the next outer scope.
3006 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003007 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003008
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003009 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003010 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003011 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3012 if (Method->isInstanceMethod()) {
3013 // For instance methods, look for ivars in the method's interface.
3014 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3015 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003016 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003017 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00003018 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003019 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003020 }
3021
3022 // We've already performed all of the name lookup that we need
3023 // to for Objective-C methods; the next context will be the
3024 // outer scope.
3025 break;
3026 }
3027
Douglas Gregor546be3c2009-12-30 17:04:44 +00003028 if (Ctx->isFunctionOrMethod())
3029 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003030
3031 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003032 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003033 }
3034 } else if (!S->getParent()) {
3035 // Look into the translation unit scope. We walk through the translation
3036 // unit's declaration context, because the Scope itself won't have all of
3037 // the declarations if we loaded a precompiled header.
3038 // FIXME: We would like the translation unit's Scope object to point to the
3039 // translation unit, so we don't need this special "if" branch. However,
3040 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003041 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003042 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003043 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003044 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003045 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003046 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003047 }
3048
Douglas Gregor546be3c2009-12-30 17:04:44 +00003049 if (Entity) {
3050 // Lookup visible declarations in any namespaces found by using
3051 // directives.
3052 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3053 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3054 for (; UI != UEnd; ++UI)
3055 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003056 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003057 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003058 }
3059
3060 // Lookup names in the parent scope.
3061 ShadowContextRAII Shadow(Visited);
3062 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3063}
3064
3065void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003066 VisibleDeclConsumer &Consumer,
3067 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003068 // Determine the set of using directives available during
3069 // unqualified name lookup.
3070 Scope *Initial = S;
3071 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003072 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003073 // Find the first namespace or translation-unit scope.
3074 while (S && !isNamespaceOrTranslationUnitScope(S))
3075 S = S->getParent();
3076
3077 UDirs.visitScopeChain(Initial, S);
3078 }
3079 UDirs.done();
3080
3081 // Look for visible declarations.
3082 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3083 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003084 if (!IncludeGlobalScope)
3085 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003086 ShadowContextRAII Shadow(Visited);
3087 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3088}
3089
3090void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003091 VisibleDeclConsumer &Consumer,
3092 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003093 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3094 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003095 if (!IncludeGlobalScope)
3096 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003097 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003098 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003099 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003100}
3101
Chris Lattner4ae493c2011-02-18 02:08:43 +00003102/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003103/// If GnuLabelLoc is a valid source location, then this is a definition
3104/// of an __label__ label name, otherwise it is a normal label definition
3105/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003106LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003107 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003108 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003109 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003110
3111 if (GnuLabelLoc.isValid()) {
3112 // Local label definitions always shadow existing labels.
3113 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3114 Scope *S = CurScope;
3115 PushOnScopeChains(Res, S, true);
3116 return cast<LabelDecl>(Res);
3117 }
3118
3119 // Not a GNU local label.
3120 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3121 // If we found a label, check to see if it is in the same context as us.
3122 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003123 if (Res && Res->getDeclContext() != CurContext)
3124 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003125 if (Res == 0) {
3126 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003127 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3128 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003129 assert(S && "Not in a function?");
3130 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003131 }
Chris Lattner337e5502011-02-18 01:27:55 +00003132 return cast<LabelDecl>(Res);
3133}
3134
3135//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003136// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003137//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003138
3139namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003140
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003141typedef llvm::SmallVector<TypoCorrection, 1> TypoResultList;
3142typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003143typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003144
3145static const unsigned MaxTypoDistanceResultSets = 5;
3146
Douglas Gregor546be3c2009-12-30 17:04:44 +00003147class TypoCorrectionConsumer : public VisibleDeclConsumer {
3148 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003149 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003150
3151 /// \brief The results found that have the smallest edit distance
3152 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003153 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003154 /// The pointer value being set to the current DeclContext indicates
3155 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003156 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003157
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003158 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159
Douglas Gregor546be3c2009-12-30 17:04:44 +00003160public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003161 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003162 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003163 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003164
Erik Verbruggend1205962011-10-06 07:27:49 +00003165 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3166 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003167 void FoundName(StringRef Name);
3168 void addKeywordResult(StringRef Keyword);
3169 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003170 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003171 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003172
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003173 typedef TypoResultsMap::iterator result_iterator;
3174 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003175 distance_iterator begin() { return CorrectionResults.begin(); }
3176 distance_iterator end() { return CorrectionResults.end(); }
3177 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3178 unsigned size() const { return CorrectionResults.size(); }
3179 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003180
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003181 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003182 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003183 }
3184
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003185 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003186 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003187 return (std::numeric_limits<unsigned>::max)();
3188
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003189 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003190 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003191 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003192
3193 TypoResultsMap &getBestResults() {
3194 return CorrectionResults.begin()->second;
3195 }
3196
Douglas Gregor546be3c2009-12-30 17:04:44 +00003197};
3198
3199}
3200
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003201void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003202 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003203 // Don't consider hidden names for typo correction.
3204 if (Hiding)
3205 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003206
Douglas Gregor546be3c2009-12-30 17:04:44 +00003207 // Only consider entities with identifiers for names, ignoring
3208 // special names (constructors, overloaded operators, selectors,
3209 // etc.).
3210 IdentifierInfo *Name = ND->getIdentifier();
3211 if (!Name)
3212 return;
3213
Douglas Gregor95f42922010-10-14 22:11:03 +00003214 FoundName(Name->getName());
3215}
3216
Chris Lattner5f9e2722011-07-23 10:55:15 +00003217void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003218 // Use a simple length-based heuristic to determine the minimum possible
3219 // edit distance. If the minimum isn't good enough, bail out early.
3220 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003221 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003222 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003223
Douglas Gregora1194772010-10-19 22:14:33 +00003224 // Compute an upper bound on the allowable edit distance, so that the
3225 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003226 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003227
Douglas Gregor546be3c2009-12-30 17:04:44 +00003228 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003229 // entity, and add the identifier to the list of results.
3230 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003231}
3232
Chris Lattner5f9e2722011-07-23 10:55:15 +00003233void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003234 // Compute the edit distance between the typo and this keyword,
3235 // and add the keyword to the list of results.
3236 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003237}
3238
Chris Lattner5f9e2722011-07-23 10:55:15 +00003239void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003240 NamedDecl *ND,
3241 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003242 NestedNameSpecifier *NNS,
3243 bool isKeyword) {
3244 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3245 if (isKeyword) TC.makeKeyword();
3246 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003247}
3248
3249void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003250 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003251 TypoResultList &CList =
3252 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003253
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003254 if (!CList.empty() && !CList.back().isResolved())
3255 CList.pop_back();
3256 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3257 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3258 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3259 RI != RIEnd; ++RI) {
3260 // If the Correction refers to a decl already in the result list,
3261 // replace the existing result if the string representation of Correction
3262 // comes before the current result alphabetically, then stop as there is
3263 // nothing more to be done to add Correction to the candidate set.
3264 if (RI->getCorrectionDecl() == NewND) {
3265 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3266 *RI = Correction;
3267 return;
3268 }
3269 }
3270 }
3271 if (CList.empty() || Correction.isResolved())
3272 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003273
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003274 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3275 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003276}
3277
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003278// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3279// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3280// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3281static void getNestedNameSpecifierIdentifiers(
3282 NestedNameSpecifier *NNS,
3283 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3284 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3285 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3286 else
3287 Identifiers.clear();
3288
3289 const IdentifierInfo *II = NULL;
3290
3291 switch (NNS->getKind()) {
3292 case NestedNameSpecifier::Identifier:
3293 II = NNS->getAsIdentifier();
3294 break;
3295
3296 case NestedNameSpecifier::Namespace:
3297 if (NNS->getAsNamespace()->isAnonymousNamespace())
3298 return;
3299 II = NNS->getAsNamespace()->getIdentifier();
3300 break;
3301
3302 case NestedNameSpecifier::NamespaceAlias:
3303 II = NNS->getAsNamespaceAlias()->getIdentifier();
3304 break;
3305
3306 case NestedNameSpecifier::TypeSpecWithTemplate:
3307 case NestedNameSpecifier::TypeSpec:
3308 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3309 break;
3310
3311 case NestedNameSpecifier::Global:
3312 return;
3313 }
3314
3315 if (II)
3316 Identifiers.push_back(II);
3317}
3318
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003319namespace {
3320
3321class SpecifierInfo {
3322 public:
3323 DeclContext* DeclCtx;
3324 NestedNameSpecifier* NameSpecifier;
3325 unsigned EditDistance;
3326
3327 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3328 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3329};
3330
Chris Lattner5f9e2722011-07-23 10:55:15 +00003331typedef SmallVector<DeclContext*, 4> DeclContextList;
3332typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003333
3334class NamespaceSpecifierSet {
3335 ASTContext &Context;
3336 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003337 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3338 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003339 bool isSorted;
3340
3341 SpecifierInfoList Specifiers;
3342 llvm::SmallSetVector<unsigned, 4> Distances;
3343 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3344
3345 /// \brief Helper for building the list of DeclContexts between the current
3346 /// context and the top of the translation unit
3347 static DeclContextList BuildContextChain(DeclContext *Start);
3348
3349 void SortNamespaces();
3350
3351 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003352 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3353 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003354 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003355 isSorted(true) {
3356 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3357 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3358 CurNameSpecifierIdentifiers);
3359 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003360 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003361 // context.
3362 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3363 CEnd = CurContextChain.rend();
3364 C != CEnd; ++C) {
3365 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3366 CurContextIdentifiers.push_back(ND->getIdentifier());
3367 }
3368 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003369
3370 /// \brief Add the namespace to the set, computing the corresponding
3371 /// NestedNameSpecifier and its distance in the process.
3372 void AddNamespace(NamespaceDecl *ND);
3373
3374 typedef SpecifierInfoList::iterator iterator;
3375 iterator begin() {
3376 if (!isSorted) SortNamespaces();
3377 return Specifiers.begin();
3378 }
3379 iterator end() { return Specifiers.end(); }
3380};
3381
3382}
3383
3384DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003385 assert(Start && "Bulding a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003386 DeclContextList Chain;
3387 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3388 DC = DC->getLookupParent()) {
3389 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3390 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3391 !(ND && ND->isAnonymousNamespace()))
3392 Chain.push_back(DC->getPrimaryContext());
3393 }
3394 return Chain;
3395}
3396
3397void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003398 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003399 sortedDistances.append(Distances.begin(), Distances.end());
3400
3401 if (sortedDistances.size() > 1)
3402 std::sort(sortedDistances.begin(), sortedDistances.end());
3403
3404 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003405 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003406 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003407 DI != DIEnd; ++DI) {
3408 SpecifierInfoList &SpecList = DistanceMap[*DI];
3409 Specifiers.append(SpecList.begin(), SpecList.end());
3410 }
3411
3412 isSorted = true;
3413}
3414
3415void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003416 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003417 NestedNameSpecifier *NNS = NULL;
3418 unsigned NumSpecifiers = 0;
3419 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003420 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003421
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003422 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003423 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3424 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003425 C != CEnd && !NamespaceDeclChain.empty() &&
3426 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003427 NamespaceDeclChain.pop_back();
3428 }
3429
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003430 // Add an explicit leading '::' specifier if needed.
3431 if (NamespaceDecl *ND =
Kaelyn Uhrain3ad02aa2012-02-15 22:59:03 +00003432 NamespaceDeclChain.empty() ? NULL :
3433 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003434 IdentifierInfo *Name = ND->getIdentifier();
3435 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3436 Name) != CurContextIdentifiers.end() ||
3437 std::find(CurNameSpecifierIdentifiers.begin(),
3438 CurNameSpecifierIdentifiers.end(),
3439 Name) != CurNameSpecifierIdentifiers.end()) {
3440 NamespaceDeclChain = FullNamespaceDeclChain;
3441 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3442 }
3443 }
3444
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003445 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3446 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3447 CEnd = NamespaceDeclChain.rend();
3448 C != CEnd; ++C) {
3449 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3450 if (ND) {
3451 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3452 ++NumSpecifiers;
3453 }
3454 }
3455
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003456 // If the built NestedNameSpecifier would be replacing an existing
3457 // NestedNameSpecifier, use the number of component identifiers that
3458 // would need to be changed as the edit distance instead of the number
3459 // of components in the built NestedNameSpecifier.
3460 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3461 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3462 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3463 NumSpecifiers = llvm::ComputeEditDistance(
3464 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3465 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3466 }
3467
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003468 isSorted = false;
3469 Distances.insert(NumSpecifiers);
3470 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003471}
3472
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003473/// \brief Perform name lookup for a possible result for typo correction.
3474static void LookupPotentialTypoResult(Sema &SemaRef,
3475 LookupResult &Res,
3476 IdentifierInfo *Name,
3477 Scope *S, CXXScopeSpec *SS,
3478 DeclContext *MemberContext,
3479 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003480 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003481 Res.suppressDiagnostics();
3482 Res.clear();
3483 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003484 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003485 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003486 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003487 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3488 Res.addDecl(Ivar);
3489 Res.resolveKind();
3490 return;
3491 }
3492 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003493
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003494 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3495 Res.addDecl(Prop);
3496 Res.resolveKind();
3497 return;
3498 }
3499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003501 SemaRef.LookupQualifiedName(Res, MemberContext);
3502 return;
3503 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504
3505 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003506 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003507
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003508 // Fake ivar lookup; this should really be part of
3509 // LookupParsedName.
3510 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3511 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003512 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003513 (Res.isSingleResult() &&
3514 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003516 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3517 Res.addDecl(IV);
3518 Res.resolveKind();
3519 }
3520 }
3521 }
3522}
3523
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003524/// \brief Add keywords to the consumer as possible typo corrections.
3525static void AddKeywordsToConsumer(Sema &SemaRef,
3526 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003527 Scope *S, CorrectionCandidateCallback &CCC,
3528 bool AfterNestedNameSpecifier) {
3529 if (AfterNestedNameSpecifier) {
3530 // For 'X::', we know exactly which keywords can appear next.
3531 Consumer.addKeywordResult("template");
3532 if (CCC.WantExpressionKeywords)
3533 Consumer.addKeywordResult("operator");
3534 return;
3535 }
3536
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003537 if (CCC.WantObjCSuper)
3538 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003539
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003540 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003541 // Add type-specifier keywords to the set of results.
3542 const char *CTypeSpecs[] = {
3543 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003544 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003545 "_Complex", "_Imaginary",
3546 // storage-specifiers as well
3547 "extern", "inline", "static", "typedef"
3548 };
3549
3550 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3551 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3552 Consumer.addKeywordResult(CTypeSpecs[I]);
3553
David Blaikie4e4d0842012-03-11 07:00:24 +00003554 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003555 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003556 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003557 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003558 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003559 Consumer.addKeywordResult("_Bool");
3560
David Blaikie4e4d0842012-03-11 07:00:24 +00003561 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003562 Consumer.addKeywordResult("class");
3563 Consumer.addKeywordResult("typename");
3564 Consumer.addKeywordResult("wchar_t");
3565
David Blaikie4e4d0842012-03-11 07:00:24 +00003566 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003567 Consumer.addKeywordResult("char16_t");
3568 Consumer.addKeywordResult("char32_t");
3569 Consumer.addKeywordResult("constexpr");
3570 Consumer.addKeywordResult("decltype");
3571 Consumer.addKeywordResult("thread_local");
3572 }
3573 }
3574
David Blaikie4e4d0842012-03-11 07:00:24 +00003575 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003576 Consumer.addKeywordResult("typeof");
3577 }
3578
David Blaikie4e4d0842012-03-11 07:00:24 +00003579 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003580 Consumer.addKeywordResult("const_cast");
3581 Consumer.addKeywordResult("dynamic_cast");
3582 Consumer.addKeywordResult("reinterpret_cast");
3583 Consumer.addKeywordResult("static_cast");
3584 }
3585
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003586 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003587 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003588 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003589 Consumer.addKeywordResult("false");
3590 Consumer.addKeywordResult("true");
3591 }
3592
David Blaikie4e4d0842012-03-11 07:00:24 +00003593 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003594 const char *CXXExprs[] = {
3595 "delete", "new", "operator", "throw", "typeid"
3596 };
3597 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3598 for (unsigned I = 0; I != NumCXXExprs; ++I)
3599 Consumer.addKeywordResult(CXXExprs[I]);
3600
3601 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3602 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3603 Consumer.addKeywordResult("this");
3604
David Blaikie4e4d0842012-03-11 07:00:24 +00003605 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003606 Consumer.addKeywordResult("alignof");
3607 Consumer.addKeywordResult("nullptr");
3608 }
3609 }
3610 }
3611
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003612 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003613 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3614 // Statements.
3615 const char *CStmts[] = {
3616 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3617 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3618 for (unsigned I = 0; I != NumCStmts; ++I)
3619 Consumer.addKeywordResult(CStmts[I]);
3620
David Blaikie4e4d0842012-03-11 07:00:24 +00003621 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003622 Consumer.addKeywordResult("catch");
3623 Consumer.addKeywordResult("try");
3624 }
3625
3626 if (S && S->getBreakParent())
3627 Consumer.addKeywordResult("break");
3628
3629 if (S && S->getContinueParent())
3630 Consumer.addKeywordResult("continue");
3631
3632 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3633 Consumer.addKeywordResult("case");
3634 Consumer.addKeywordResult("default");
3635 }
3636 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003637 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003638 Consumer.addKeywordResult("namespace");
3639 Consumer.addKeywordResult("template");
3640 }
3641
3642 if (S && S->isClassScope()) {
3643 Consumer.addKeywordResult("explicit");
3644 Consumer.addKeywordResult("friend");
3645 Consumer.addKeywordResult("mutable");
3646 Consumer.addKeywordResult("private");
3647 Consumer.addKeywordResult("protected");
3648 Consumer.addKeywordResult("public");
3649 Consumer.addKeywordResult("virtual");
3650 }
3651 }
3652
David Blaikie4e4d0842012-03-11 07:00:24 +00003653 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003654 Consumer.addKeywordResult("using");
3655
David Blaikie4e4d0842012-03-11 07:00:24 +00003656 if (SemaRef.getLangOpts().CPlusPlus0x)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003657 Consumer.addKeywordResult("static_assert");
3658 }
3659 }
3660}
3661
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003662static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3663 TypoCorrection &Candidate) {
3664 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3665 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3666}
3667
Douglas Gregor546be3c2009-12-30 17:04:44 +00003668/// \brief Try to "correct" a typo in the source code by finding
3669/// visible declarations whose names are similar to the name that was
3670/// present in the source code.
3671///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003672/// \param TypoName the \c DeclarationNameInfo structure that contains
3673/// the name that was present in the source code along with its location.
3674///
3675/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003676///
3677/// \param S the scope in which name lookup occurs.
3678///
3679/// \param SS the nested-name-specifier that precedes the name we're
3680/// looking for, if present.
3681///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003682/// \param CCC A CorrectionCandidateCallback object that provides further
3683/// validation of typo correction candidates. It also provides flags for
3684/// determining the set of keywords permitted.
3685///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003686/// \param MemberContext if non-NULL, the context in which to look for
3687/// a member access expression.
3688///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003689/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003690/// the nested-name-specifier SS.
3691///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003692/// \param OPT when non-NULL, the search for visible declarations will
3693/// also walk the protocols in the qualified interfaces of \p OPT.
3694///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003695/// \returns a \c TypoCorrection containing the corrected name if the typo
3696/// along with information such as the \c NamedDecl where the corrected name
3697/// was declared, and any additional \c NestedNameSpecifier needed to access
3698/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3699TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3700 Sema::LookupNameKind LookupKind,
3701 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003702 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003703 DeclContext *MemberContext,
3704 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003705 const ObjCObjectPointerType *OPT) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003706 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003707 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708
Francois Pichet4d604d62011-12-03 15:55:29 +00003709 // In Microsoft mode, don't perform typo correction in a template member
3710 // function dependent context because it interferes with the "lookup into
3711 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003712 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003713 isa<CXXMethodDecl>(CurContext))
3714 return TypoCorrection();
3715
Douglas Gregor546be3c2009-12-30 17:04:44 +00003716 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003717 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003718 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003719 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003720
3721 // If the scope specifier itself was invalid, don't try to correct
3722 // typos.
3723 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003724 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003725
3726 // Never try to correct typos during template deduction or
3727 // instantiation.
3728 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003729 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003730
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003731 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003732
3733 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003734
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003735 // If a callback object considers an empty typo correction candidate to be
3736 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003737 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003738 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003739
Douglas Gregoraaf87162010-04-14 20:04:41 +00003740 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003741 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003742 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003743 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003744 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003745
3746 // Look in qualified interfaces.
3747 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003748 for (ObjCObjectPointerType::qual_iterator
3749 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003750 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003751 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003752 }
3753 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003754 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3755 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003756 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003757
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003758 // Provide a stop gap for files that are just seriously broken. Trying
3759 // to correct all typos can turn into a HUGE performance penalty, causing
3760 // some files to take minutes to get rejected by the parser.
3761 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003762 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003763 ++TyposCorrected;
3764
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003765 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003766 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003767 IsUnqualifiedLookup = true;
3768 UnqualifiedTyposCorrectedMap::iterator Cached
3769 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003770 if (Cached != UnqualifiedTyposCorrected.end()) {
3771 // Add the cached value, unless it's a keyword or fails validation. In the
3772 // keyword case, we'll end up adding the keyword below.
3773 if (Cached->second) {
3774 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003775 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003776 Consumer.addCorrection(Cached->second);
3777 } else {
3778 // Only honor no-correction cache hits when a callback that will validate
3779 // correction candidates is not being used.
3780 if (!ValidatingCallback)
3781 return TypoCorrection();
3782 }
3783 }
3784 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003785 // Provide a stop gap for files that are just seriously broken. Trying
3786 // to correct all typos can turn into a HUGE performance penalty, causing
3787 // some files to take minutes to get rejected by the parser.
3788 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003789 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003790 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003791 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792
Douglas Gregor01798682012-03-26 16:54:18 +00003793 // Determine whether we are going to search in the various namespaces for
3794 // corrections.
3795 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00003796 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00003797 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003798 // In a few cases we *only* want to search for corrections bases on just
3799 // adding or changing the nested name specifier.
3800 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00003801
3802 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003803 // For unqualified lookup, look through all of the names that we have
3804 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003805 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003806 for (IdentifierTable::iterator I = Context.Idents.begin(),
3807 IEnd = Context.Idents.end();
3808 I != IEnd; ++I)
3809 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003810
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003811 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003812 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003813 if (IdentifierInfoLookup *External
3814 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003815 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003816 do {
3817 StringRef Name = Iter->Next();
3818 if (Name.empty())
3819 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003820
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003821 Consumer.FoundName(Name);
3822 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00003823 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003824 }
3825
Richard Smith0f4b5be2012-06-08 21:35:42 +00003826 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003827
Douglas Gregoraaf87162010-04-14 20:04:41 +00003828 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003829 if (Consumer.empty()) {
3830 // If this was an unqualified lookup, note that no correction was found.
3831 if (IsUnqualifiedLookup)
3832 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003833
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003834 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003835 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003836
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003837 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3838 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003839 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003840 if (ED > 0 && Typo->getName().size() / ED < 3) {
3841 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003842 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003843 (void)UnqualifiedTyposCorrected[Typo];
3844
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003845 return TypoCorrection();
3846 }
3847
Douglas Gregor01798682012-03-26 16:54:18 +00003848 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3849 // to search those namespaces.
3850 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003851 // Load any externally-known namespaces.
3852 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003853 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003854 LoadedExternalKnownNamespaces = true;
3855 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3856 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3857 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3858 }
3859
3860 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3861 KNI = KnownNamespaces.begin(),
3862 KNIEnd = KnownNamespaces.end();
3863 KNI != KNIEnd; ++KNI)
3864 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003865 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003866
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003867 // Weed out any names that could not be found by name lookup or, if a
3868 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003869 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003870 LookupResult TmpRes(*this, TypoName, LookupKind);
3871 TmpRes.suppressDiagnostics();
3872 while (!Consumer.empty()) {
3873 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3874 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003875 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3876 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003877 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003878 // If we only want nested name specifier corrections, ignore potential
3879 // corrections that have a different base identifier from the typo.
3880 if (AllowOnlyNNSChanges &&
3881 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3882 TypoCorrectionConsumer::result_iterator Prev = I;
3883 ++I;
3884 DI->second.erase(Prev);
3885 continue;
3886 }
3887
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003888 // If the item already has been looked up or is a keyword, keep it.
3889 // If a validator callback object was given, drop the correction
3890 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003891 bool Viable = false;
3892 for (TypoResultList::iterator RI = I->second.begin(), RIEnd = I->second.end();
3893 RI != RIEnd; /* Increment in loop. */) {
3894 TypoResultList::iterator Prev = RI;
3895 ++RI;
3896 if (Prev->isResolved()) {
3897 if (!isCandidateViable(CCC, *Prev))
3898 I->second.erase(Prev);
3899 else
3900 Viable = true;
3901 }
3902 }
3903 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003904 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003905 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003906 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003907 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003908 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003909 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003910 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003911
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003912 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003913 TypoCorrection &Candidate = I->second.front();
3914 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003915 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003916 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003917
3918 switch (TmpRes.getResultKind()) {
3919 case LookupResult::NotFound:
3920 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003921 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003922 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003923 // We didn't find this name in our scope, or didn't like what we found;
3924 // ignore it.
3925 {
3926 TypoCorrectionConsumer::result_iterator Next = I;
3927 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003928 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003929 I = Next;
3930 }
3931 break;
3932
3933 case LookupResult::Ambiguous:
3934 // We don't deal with ambiguities.
3935 return TypoCorrection();
3936
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003937 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003938 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003939 // Store all of the Decls for overloaded symbols
3940 for (LookupResult::iterator TRD = TmpRes.begin(),
3941 TRDEnd = TmpRes.end();
3942 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003943 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003944 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003945 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003946 DI->second.erase(Prev);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003947 break;
3948 }
3949
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003950 case LookupResult::Found: {
3951 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003952 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +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);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003956 break;
3957 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003958
3959 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003960 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003961
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003962 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003963 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00003964 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003965 // If there are results in the closest possible bucket, stop
3966 break;
3967
3968 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00003969 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003970 TmpRes.suppressDiagnostics();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003971 for (llvm::SmallVector<TypoCorrection,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003972 16>::iterator QRI = QualifiedResults.begin(),
3973 QRIEnd = QualifiedResults.end();
3974 QRI != QRIEnd; ++QRI) {
3975 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3976 NIEnd = Namespaces.end();
3977 NI != NIEnd; ++NI) {
3978 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003979
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003980 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003981 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003982 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003983
3984 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003985 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003986 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3987
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003988 // Any corrections added below will be validated in subsequent
3989 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003990 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003991 case LookupResult::Found: {
3992 TypoCorrection TC(*QRI);
3993 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3994 TC.setCorrectionSpecifier(NI->NameSpecifier);
3995 TC.setQualifierDistance(NI->EditDistance);
3996 Consumer.addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003997 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003998 }
3999 case LookupResult::FoundOverloaded: {
4000 TypoCorrection TC(*QRI);
4001 TC.setCorrectionSpecifier(NI->NameSpecifier);
4002 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004003 for (LookupResult::iterator TRD = TmpRes.begin(),
4004 TRDEnd = TmpRes.end();
4005 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004006 TC.addCorrectionDecl(*TRD);
4007 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004008 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004009 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004010 case LookupResult::NotFound:
4011 case LookupResult::NotFoundInCurrentInstantiation:
4012 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004013 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004014 break;
4015 }
4016 }
4017 }
4018 }
4019
4020 QualifiedResults.clear();
4021 }
4022
4023 // No corrections remain...
4024 if (Consumer.empty()) return TypoCorrection();
4025
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004026 TypoResultsMap &BestResults = Consumer.getBestResults();
4027 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004028
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004029 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004030 // If this was an unqualified lookup and we believe the callback
4031 // object wouldn't have filtered out possible corrections, note
4032 // that no correction was found.
4033 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004034 (void)UnqualifiedTyposCorrected[Typo];
4035
4036 return TypoCorrection();
4037 }
4038
Douglas Gregore24b5752010-10-14 20:34:08 +00004039 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004040 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004041 const TypoResultList &CorrectionList = BestResults.begin()->second;
4042 const TypoCorrection &Result = CorrectionList.front();
4043 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044
Douglas Gregor53e4b552010-10-26 17:18:00 +00004045 // Don't correct to a keyword that's the same as the typo; the keyword
4046 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004047 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4048
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004049 // Record the correction for unqualified lookup.
4050 if (IsUnqualifiedLookup)
4051 UnqualifiedTyposCorrected[Typo] = Result;
4052
4053 return Result;
4054 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004055 else if (BestResults.size() > 1
4056 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4057 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4058 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4059 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004060 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004061 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004062 // Prefer 'super' when we're completing in a message-receiver
4063 // context.
4064
4065 // Don't correct to a keyword that's the same as the typo; the keyword
4066 // wasn't actually in scope.
4067 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004068
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004069 // Record the correction for unqualified lookup.
4070 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004071 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004072
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004073 return BestResults["super"].front();
Douglas Gregor7b824e82010-10-15 13:35:25 +00004074 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004075
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004076 // If this was an unqualified lookup and we believe the callback object did
4077 // not filter out possible corrections, note that no correction was found.
4078 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004079 (void)UnqualifiedTyposCorrected[Typo];
4080
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004081 return TypoCorrection();
4082}
4083
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004084void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4085 if (!CDecl) return;
4086
4087 if (isKeyword())
4088 CorrectionDecls.clear();
4089
4090 CorrectionDecls.push_back(CDecl);
4091
4092 if (!CorrectionName)
4093 CorrectionName = CDecl->getDeclName();
4094}
4095
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004096std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4097 if (CorrectionNameSpec) {
4098 std::string tmpBuffer;
4099 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4100 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004101 CorrectionName.printName(PrefixOStream);
4102 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004103 }
4104
4105 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004106}