blob: 5b641d80598959b31c5413239bfe3027a41c813c [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewycky173a37a2012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ExternalSemaSource.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/TemplateDeduction.h"
34#include "clang/Sema/TypoCorrection.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/ADT/SetVector.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000038#include "llvm/ADT/StringMap.h"
Chris Lattnerb5f65472011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6e247262009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Nick Lewycky893a6ea2012-04-03 20:26:45 +000042#include <algorithm>
43#include <iterator>
Douglas Gregore24b5752010-10-14 20:34:08 +000044#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000045#include <list>
Douglas Gregord8bba9c2011-06-28 16:20:02 +000046#include <map>
Nick Lewycky893a6ea2012-04-03 20:26:45 +000047#include <set>
48#include <utility>
49#include <vector>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000050
51using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000052using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054namespace {
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000058
John McCalld7be78a2009-11-10 07:01:13 +000059 public:
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000064
John McCalld7be78a2009-11-10 07:01:13 +000065 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
67 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000068
John McCalld7be78a2009-11-10 07:01:13 +000069 const DeclContext *getNominatedNamespace() const {
70 return Nominated;
71 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000072
John McCalld7be78a2009-11-10 07:01:13 +000073 // Sort by the pointer value of the common ancestor.
74 struct Comparator {
75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76 return L.getCommonAncestor() < R.getCommonAncestor();
77 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000078
John McCalld7be78a2009-11-10 07:01:13 +000079 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
81 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000082
John McCalld7be78a2009-11-10 07:01:13 +000083 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
85 }
86 };
87 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000088
John McCalld7be78a2009-11-10 07:01:13 +000089 /// A collection of using directives, as used by C++ unqualified
90 /// lookup.
91 class UnqualUsingDirectiveSet {
Chris Lattner5f9e2722011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000096
John McCalld7be78a2009-11-10 07:01:13 +000097 public:
98 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000099
John McCalld7be78a2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCalld7be78a2009-11-10 07:01:13 +0000102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
105 DeclContext *InnermostFileDC
106 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000108
John McCalld7be78a2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky65daef12012-03-13 04:12:34 +0000110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000113 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
Nick Lewycky65daef12012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
John McCalld7be78a2009-11-10 07:01:13 +0000117 Scope::udir_iterator I = S->using_directives_begin(),
118 End = S->using_directives_end();
John McCalld7be78a2009-11-10 07:01:13 +0000119 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000120 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000121 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000122 }
123 }
John McCalld7be78a2009-11-10 07:01:13 +0000124
125 // Visits a context and collect all of its using directives
126 // recursively. Treats all using directives as if they were
127 // declared in the context.
128 //
129 // A given context is only every visited once, so it is important
130 // that contexts be visited from the inside out in order to get
131 // the effective DCs right.
132 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
133 if (!visited.insert(DC))
134 return;
135
136 addUsingDirectives(DC, EffectiveDC);
137 }
138
139 // Visits a using directive and collects all of its using
140 // directives recursively. Treats all using directives as if they
141 // were declared in the effective DC.
142 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (!visited.insert(NS))
145 return;
146
147 addUsingDirective(UD, EffectiveDC);
148 addUsingDirectives(NS, EffectiveDC);
149 }
150
151 // Adds all the using directives in a context (and those nominated
152 // by its using directives, transitively) as if they appeared in
153 // the given effective context.
154 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000155 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-11-10 07:01:13 +0000156 while (true) {
157 DeclContext::udir_iterator I, End;
158 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
159 UsingDirectiveDecl *UD = *I;
160 DeclContext *NS = UD->getNominatedNamespace();
161 if (visited.insert(NS)) {
162 addUsingDirective(UD, EffectiveDC);
163 queue.push_back(NS);
164 }
165 }
166
167 if (queue.empty())
168 return;
169
Robert Wilhelm344472e2013-08-23 16:11:15 +0000170 DC = queue.pop_back_val();
John McCalld7be78a2009-11-10 07:01:13 +0000171 }
172 }
173
174 // Add a using directive as if it had been declared in the given
175 // context. This helps implement C++ [namespace.udir]p3:
176 // The using-directive is transitive: if a scope contains a
177 // using-directive that nominates a second namespace that itself
178 // contains using-directives, the effect is as if the
179 // using-directives from the second namespace also appeared in
180 // the first.
181 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
182 // Find the common ancestor between the effective context and
183 // the nominated namespace.
184 DeclContext *Common = UD->getNominatedNamespace();
185 while (!Common->Encloses(EffectiveDC))
186 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000187 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000188
John McCalld7be78a2009-11-10 07:01:13 +0000189 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
190 }
191
192 void done() {
193 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
194 }
195
John McCalld7be78a2009-11-10 07:01:13 +0000196 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000197
John McCalld7be78a2009-11-10 07:01:13 +0000198 const_iterator begin() const { return list.begin(); }
199 const_iterator end() const { return list.end(); }
200
201 std::pair<const_iterator,const_iterator>
202 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000203 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000204 UnqualUsingEntry::Comparator());
205 }
206 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000207}
208
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000209// Retrieve the set of identifier namespaces that correspond to a
210// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000211static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
212 bool CPlusPlus,
213 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000214 unsigned IDNS = 0;
215 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000216 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000217 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000218 case Sema::LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +0000219 case Sema::LookupLocalFriendName:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000220 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000221 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000222 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000223 if (Redeclaration)
224 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000225 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000226 break;
227
John McCall76d32642010-04-24 01:30:58 +0000228 case Sema::LookupOperatorName:
229 // Operator lookup is its own crazy thing; it is not the same
230 // as (e.g.) looking up an operator name for redeclaration.
231 assert(!Redeclaration && "cannot do redeclaration operator lookup");
232 IDNS = Decl::IDNS_NonMemberOperator;
233 break;
234
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000235 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000236 if (CPlusPlus) {
237 IDNS = Decl::IDNS_Type;
238
239 // When looking for a redeclaration of a tag name, we add:
240 // 1) TagFriend to find undeclared friend decls
241 // 2) Namespace because they can't "overload" with tag decls.
242 // 3) Tag because it includes class templates, which can't
243 // "overload" with tag decls.
244 if (Redeclaration)
245 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
246 } else {
247 IDNS = Decl::IDNS_Tag;
248 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000249 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000250 case Sema::LookupLabel:
251 IDNS = Decl::IDNS_Label;
252 break;
253
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000254 case Sema::LookupMemberName:
255 IDNS = Decl::IDNS_Member;
256 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000257 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000258 break;
259
260 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
262 break;
263
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000264 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000265 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000266 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000267
John McCall9f54ad42009-12-10 09:41:52 +0000268 case Sema::LookupUsingDeclName:
269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
270 | Decl::IDNS_Member | Decl::IDNS_Using;
271 break;
272
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000273 case Sema::LookupObjCProtocolName:
274 IDNS = Decl::IDNS_ObjCProtocol;
275 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276
Douglas Gregor8071e422010-08-15 06:18:01 +0000277 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000278 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000279 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
280 | Decl::IDNS_Type;
281 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000282 }
283 return IDNS;
284}
285
John McCall1d7c5282009-12-18 10:40:03 +0000286void LookupResult::configure() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000287 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000288 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000289
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000290 if (!isForRedeclaration()) {
Douglas Gregor96df3562013-04-03 23:06:26 +0000291 // If we're looking for one of the allocation or deallocation
292 // operators, make sure that the implicitly-declared new and delete
293 // operators can be found.
Abramo Bagnara25777432010-08-11 22:01:17 +0000294 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000295 case OO_New:
296 case OO_Delete:
297 case OO_Array_New:
298 case OO_Array_Delete:
299 SemaRef.DeclareGlobalNewDelete();
300 break;
301
302 default:
303 break;
304 }
Douglas Gregor96df3562013-04-03 23:06:26 +0000305
306 // Compiler builtins are always visible, regardless of where they end
307 // up being declared.
308 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
309 if (unsigned BuiltinID = Id->getBuiltinID()) {
310 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
311 AllowHidden = true;
312 }
313 }
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000314 }
John McCall1d7c5282009-12-18 10:40:03 +0000315}
316
Daniel Dunbarc2bd73b2012-03-08 01:43:06 +0000317void LookupResult::sanityImpl() const {
318 // Note that this function is never called by NDEBUG builds. See
319 // LookupResult::sanity().
John McCall2a7fb272010-08-25 05:32:35 +0000320 assert(ResultKind != NotFound || Decls.size() == 0);
321 assert(ResultKind != Found || Decls.size() == 1);
322 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
323 (Decls.size() == 1 &&
324 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
325 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
326 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000327 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
328 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000329 assert((Paths != NULL) == (ResultKind == Ambiguous &&
330 (Ambiguity == AmbiguousBaseSubobjectTypes ||
331 Ambiguity == AmbiguousBaseSubobjects)));
332}
John McCall2a7fb272010-08-25 05:32:35 +0000333
John McCallf36e02d2009-10-09 21:13:30 +0000334// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000335void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000336 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000337}
338
John McCall7453ed42009-11-22 00:44:51 +0000339/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000340void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000341 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000342
John McCallf36e02d2009-10-09 21:13:30 +0000343 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000344 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000345 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000346 return;
347 }
348
John McCall7453ed42009-11-22 00:44:51 +0000349 // If there's a single decl, we need to examine it to decide what
350 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000351 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000352 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
353 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000354 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000355 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000356 ResultKind = FoundUnresolvedValue;
357 return;
358 }
John McCallf36e02d2009-10-09 21:13:30 +0000359
John McCall6e247262009-10-10 05:48:19 +0000360 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000361 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000362
John McCallf36e02d2009-10-09 21:13:30 +0000363 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000364 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000365
John McCallf36e02d2009-10-09 21:13:30 +0000366 bool Ambiguous = false;
367 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000368 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000369
370 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000371
John McCallf36e02d2009-10-09 21:13:30 +0000372 unsigned I = 0;
373 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000374 NamedDecl *D = Decls[I]->getUnderlyingDecl();
375 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000376
Argyrios Kyrtzidis745af1c2013-02-22 06:58:37 +0000377 // Ignore an invalid declaration unless it's the only one left.
378 if (D->isInvalidDecl() && I < N-1) {
379 Decls[I] = Decls[--N];
380 continue;
381 }
382
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000383 // Redeclarations of types via typedef can occur both within a scope
384 // and, through using declarations and directives, across scopes. There is
385 // no ambiguity if they all refer to the same type, so unique based on the
386 // canonical type.
387 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
388 if (!TD->getDeclContext()->isRecord()) {
389 QualType T = SemaRef.Context.getTypeDeclType(TD);
390 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
391 // The type is not unique; pull something off the back and continue
392 // at this index.
393 Decls[I] = Decls[--N];
394 continue;
395 }
396 }
397 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000398
John McCall314be4e2009-11-17 07:50:12 +0000399 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000400 // If it's not unique, pull something off the back (and
401 // continue at this index).
402 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000403 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000404 }
405
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000406 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000407
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000408 if (isa<UnresolvedUsingValueDecl>(D)) {
409 HasUnresolved = true;
410 } else if (isa<TagDecl>(D)) {
411 if (HasTag)
412 Ambiguous = true;
413 UniqueTagIndex = I;
414 HasTag = true;
415 } else if (isa<FunctionTemplateDecl>(D)) {
416 HasFunction = true;
417 HasFunctionTemplate = true;
418 } else if (isa<FunctionDecl>(D)) {
419 HasFunction = true;
420 } else {
421 if (HasNonFunction)
422 Ambiguous = true;
423 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000424 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000425 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000426 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000427
John McCallf36e02d2009-10-09 21:13:30 +0000428 // C++ [basic.scope.hiding]p2:
429 // A class name or enumeration name can be hidden by the name of
430 // an object, function, or enumerator declared in the same
431 // scope. If a class or enumeration name and an object, function,
432 // or enumerator are declared in the same scope (in any order)
433 // with the same name, the class or enumeration name is hidden
434 // wherever the object, function, or enumerator name is visible.
435 // But it's still an error if there are distinct tag types found,
436 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000437 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000438 (HasFunction || HasNonFunction || HasUnresolved)) {
439 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
440 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
441 Decls[UniqueTagIndex] = Decls[--N];
442 else
443 Ambiguous = true;
444 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000445
John McCallf36e02d2009-10-09 21:13:30 +0000446 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000447
John McCallfda8e122009-12-03 00:58:24 +0000448 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000449 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000450
John McCallf36e02d2009-10-09 21:13:30 +0000451 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000452 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000453 else if (HasUnresolved)
454 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000455 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000456 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000457 else
John McCalla24dc2e2009-11-17 02:14:36 +0000458 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000459}
460
John McCall7d384dd2009-11-18 07:57:50 +0000461void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000462 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000463 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikie3bc93e32012-12-19 00:45:41 +0000464 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
465 DE = I->Decls.end(); DI != DE; ++DI)
John McCallf36e02d2009-10-09 21:13:30 +0000466 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000467}
468
John McCall7d384dd2009-11-18 07:57:50 +0000469void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000470 Paths = new CXXBasePaths;
471 Paths->swap(P);
472 addDeclsFromBasePaths(*Paths);
473 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000474 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000475}
476
John McCall7d384dd2009-11-18 07:57:50 +0000477void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000478 Paths = new CXXBasePaths;
479 Paths->swap(P);
480 addDeclsFromBasePaths(*Paths);
481 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000482 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000483}
484
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000486 Out << Decls.size() << " result(s)";
487 if (isAmbiguous()) Out << ", ambiguous";
488 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000489
John McCallf36e02d2009-10-09 21:13:30 +0000490 for (iterator I = begin(), E = end(); I != E; ++I) {
491 Out << "\n";
492 (*I)->print(Out, 2);
493 }
494}
495
Douglas Gregor85910982010-02-12 05:48:04 +0000496/// \brief Lookup a builtin function, when name lookup would otherwise
497/// fail.
498static bool LookupBuiltin(Sema &S, LookupResult &R) {
499 Sema::LookupNameKind NameKind = R.getLookupKind();
500
501 // If we didn't find a use of this identifier, and if the identifier
502 // corresponds to a compiler builtin, create the decl object for the builtin
503 // now, injecting it into translation unit scope, and return it.
504 if (NameKind == Sema::LookupOrdinaryName ||
505 NameKind == Sema::LookupRedeclarationWithLinkage) {
506 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
507 if (II) {
Nico Webercac18ad2013-06-20 21:44:55 +0000508 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
509 II == S.getFloat128Identifier()) {
510 // libstdc++4.7's type_traits expects type __float128 to exist, so
511 // insert a dummy type to make that header build in gnu++11 mode.
512 R.addDecl(S.getASTContext().getFloat128StubType());
513 return true;
514 }
515
Douglas Gregor85910982010-02-12 05:48:04 +0000516 // If this is a builtin on this (or all) targets, create the decl.
517 if (unsigned BuiltinID = II->getBuiltinID()) {
518 // In C++, we don't have any predefined library functions like
519 // 'malloc'. Instead, we'll just error.
David Blaikie4e4d0842012-03-11 07:00:24 +0000520 if (S.getLangOpts().CPlusPlus &&
Douglas Gregor85910982010-02-12 05:48:04 +0000521 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
522 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000523
524 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
525 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000526 R.isForRedeclaration(),
527 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000528 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000529 return true;
530 }
531
532 if (R.isForRedeclaration()) {
533 // If we're redeclaring this function anyway, forget that
534 // this was a builtin at all.
535 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
536 }
537
538 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000539 }
540 }
541 }
542
543 return false;
544}
545
Douglas Gregor4923aa22010-07-02 20:37:36 +0000546/// \brief Determine whether we can declare a special member function within
547/// the class at this point.
Richard Smithd0adeb62012-11-27 21:20:31 +0000548static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +0000549 // We need to have a definition for the class.
550 if (!Class->getDefinition() || Class->isDependentContext())
551 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000552
Douglas Gregor4923aa22010-07-02 20:37:36 +0000553 // We can't be in the middle of defining the class.
Richard Smithd0adeb62012-11-27 21:20:31 +0000554 return !Class->isBeingDefined();
Douglas Gregor4923aa22010-07-02 20:37:36 +0000555}
556
557void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000558 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregor22584312010-07-02 23:41:54 +0000559 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000560
561 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000562 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000563 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000564
Douglas Gregor22584312010-07-02 23:41:54 +0000565 // If the copy constructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000566 if (Class->needsImplicitCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +0000567 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregora376d102010-07-02 21:50:04 +0000569 // If the copy assignment operator has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000570 if (Class->needsImplicitCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000571 DeclareImplicitCopyAssignment(Class);
572
Richard Smith80ad52f2013-01-02 11:42:31 +0000573 if (getLangOpts().CPlusPlus11) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000574 // If the move constructor has not yet been declared, do so now.
575 if (Class->needsImplicitMoveConstructor())
576 DeclareImplicitMoveConstructor(Class); // might not actually do it
577
578 // If the move assignment operator has not yet been declared, do so now.
579 if (Class->needsImplicitMoveAssignment())
580 DeclareImplicitMoveAssignment(Class); // might not actually do it
581 }
582
Douglas Gregor4923aa22010-07-02 20:37:36 +0000583 // If the destructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000584 if (Class->needsImplicitDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000585 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000586}
587
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000588/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000589/// special member function.
590static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
591 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000592 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000593 case DeclarationName::CXXDestructorName:
594 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000595
Douglas Gregora376d102010-07-02 21:50:04 +0000596 case DeclarationName::CXXOperatorName:
597 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598
Douglas Gregora376d102010-07-02 21:50:04 +0000599 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000600 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000601 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000602
Douglas Gregora376d102010-07-02 21:50:04 +0000603 return false;
604}
605
606/// \brief If there are any implicit member functions with the given name
607/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000608static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000609 DeclarationName Name,
610 const DeclContext *DC) {
611 if (!DC)
612 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000613
Douglas Gregora376d102010-07-02 21:50:04 +0000614 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000615 case DeclarationName::CXXConstructorName:
616 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithd0adeb62012-11-27 21:20:31 +0000617 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000618 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000619 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000620 S.DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +0000621 if (Record->needsImplicitCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000622 S.DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000623 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000624 Record->needsImplicitMoveConstructor())
625 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000626 }
Douglas Gregor22584312010-07-02 23:41:54 +0000627 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000628
Douglas Gregora376d102010-07-02 21:50:04 +0000629 case DeclarationName::CXXDestructorName:
630 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithe5411b72012-12-01 02:35:44 +0000631 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smithd0adeb62012-11-27 21:20:31 +0000632 CanDeclareSpecialMemberFunction(Record))
Douglas Gregora376d102010-07-02 21:50:04 +0000633 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000634 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000635
Douglas Gregora376d102010-07-02 21:50:04 +0000636 case DeclarationName::CXXOperatorName:
637 if (Name.getCXXOverloadedOperator() != OO_Equal)
638 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000640 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000641 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000642 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smithe5411b72012-12-01 02:35:44 +0000643 if (Record->needsImplicitCopyAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000644 S.DeclareImplicitCopyAssignment(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000645 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000646 Record->needsImplicitMoveAssignment())
647 S.DeclareImplicitMoveAssignment(Class);
648 }
649 }
Douglas Gregora376d102010-07-02 21:50:04 +0000650 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000651
Douglas Gregora376d102010-07-02 21:50:04 +0000652 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000653 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000654 }
655}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000656
John McCallf36e02d2009-10-09 21:13:30 +0000657// Adds all qualifying matches for a name within a decl context to the
658// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000659static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000660 bool Found = false;
661
Douglas Gregor4923aa22010-07-02 20:37:36 +0000662 // Lazily declare C++ special member functions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000663 if (S.getLangOpts().CPlusPlus)
Douglas Gregora376d102010-07-02 21:50:04 +0000664 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000665
Douglas Gregor4923aa22010-07-02 20:37:36 +0000666 // Perform lookup into this declaration context.
David Blaikie3bc93e32012-12-19 00:45:41 +0000667 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
668 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
669 ++I) {
John McCall46460a62010-01-20 21:53:11 +0000670 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000671 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000672 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000673 Found = true;
674 }
675 }
John McCallf36e02d2009-10-09 21:13:30 +0000676
Douglas Gregor85910982010-02-12 05:48:04 +0000677 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
678 return true;
679
Douglas Gregor48026d22010-01-11 18:40:55 +0000680 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000681 != DeclarationName::CXXConversionFunctionName ||
682 R.getLookupName().getCXXNameType()->isDependentType() ||
683 !isa<CXXRecordDecl>(DC))
684 return Found;
685
686 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000687 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000688 // name lookup. Instead, any conversion function templates visible in the
689 // context of the use are considered. [...]
690 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000691 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000692 return Found;
693
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +0000694 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
695 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000696 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
697 if (!ConvTemplate)
698 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000699
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000700 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000701 // add the conversion function template. When we deduce template
702 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000703 // type of the new declaration with the type of the function template.
704 if (R.isForRedeclaration()) {
705 R.addDecl(ConvTemplate);
706 Found = true;
707 continue;
708 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000709
Douglas Gregor48026d22010-01-11 18:40:55 +0000710 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000711 // [...] For each such operator, if argument deduction succeeds
712 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000713 // name lookup.
714 //
715 // When referencing a conversion function for any purpose other than
716 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000717 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000718 // specialization into the result set. We do this to avoid forcing all
719 // callers to perform special deduction for conversion functions.
Craig Topper93e45992012-09-19 02:26:47 +0000720 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000721 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000722
723 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000724 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
725 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000726
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000727 // Compute the type of the function that we would expect the conversion
728 // function to have, if it were to match the name given.
729 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000730 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckneref072032013-08-27 23:08:25 +0000731 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000732 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000733 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000734 QualType ExpectedType
735 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko55431692013-05-05 00:41:58 +0000736 None, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000737
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000738 // Perform template argument deduction against the type that we would
739 // expect the function to have.
740 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
741 Specialization, Info)
742 == Sema::TDK_Success) {
743 R.addDecl(Specialization);
744 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000745 }
746 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000747
John McCallf36e02d2009-10-09 21:13:30 +0000748 return Found;
749}
750
John McCalld7be78a2009-11-10 07:01:13 +0000751// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000752static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000753CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000754 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000755
756 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
757
John McCalld7be78a2009-11-10 07:01:13 +0000758 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000759 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000760
John McCalld7be78a2009-11-10 07:01:13 +0000761 // Perform direct name lookup into the namespaces nominated by the
762 // using directives whose common ancestor is this namespace.
763 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
764 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000765
John McCalld7be78a2009-11-10 07:01:13 +0000766 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000767 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000768 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000769
770 R.resolveKind();
771
772 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000773}
774
775static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000776 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000777 return Ctx->isFileContext();
778 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000779}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000780
Douglas Gregor711be1e2010-03-15 14:33:29 +0000781// Find the next outer declaration context from this scope. This
782// routine actually returns the semantic outer context, which may
783// differ from the lexical context (encoded directly in the Scope
784// stack) when we are parsing a member of a class template. In this
785// case, the second element of the pair will be true, to indicate that
786// name lookup should continue searching in this semantic context when
787// it leaves the current template parameter scope.
788static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
789 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
790 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000791 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000792 OuterS = OuterS->getParent()) {
793 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000794 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000795 break;
796 }
797 }
798
799 // C++ [temp.local]p8:
800 // In the definition of a member of a class template that appears
801 // outside of the namespace containing the class template
802 // definition, the name of a template-parameter hides the name of
803 // a member of this namespace.
804 //
805 // Example:
806 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000807 // namespace N {
808 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000809 //
810 // template<class T> class B {
811 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000812 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000813 // }
814 //
815 // template<class C> void N::B<C>::f(C) {
816 // C b; // C is the template parameter, not N::C
817 // }
818 //
819 // In this example, the lexical context we return is the
820 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000821 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000822 !S->getParent()->isTemplateParamScope())
823 return std::make_pair(Lexical, false);
824
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000825 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000826 // For the example, this is the scope for the template parameters of
827 // template<class C>.
828 Scope *OutermostTemplateScope = S->getParent();
829 while (OutermostTemplateScope->getParent() &&
830 OutermostTemplateScope->getParent()->isTemplateParamScope())
831 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000832
Douglas Gregor711be1e2010-03-15 14:33:29 +0000833 // Find the namespace context in which the original scope occurs. In
834 // the example, this is namespace N.
835 DeclContext *Semantic = DC;
836 while (!Semantic->isFileContext())
837 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000838
Douglas Gregor711be1e2010-03-15 14:33:29 +0000839 // Find the declaration context just outside of the template
840 // parameter scope. This is the context in which the template is
841 // being lexically declaration (a namespace context). In the
842 // example, this is the global scope.
843 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
844 Lexical->Encloses(Semantic))
845 return std::make_pair(Semantic, true);
846
847 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000848}
849
John McCalla24dc2e2009-11-17 02:14:36 +0000850bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000851 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000852
853 DeclarationName Name = R.getLookupName();
Richard Smithdd9459f2013-08-13 18:18:50 +0000854 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCalla24dc2e2009-11-17 02:14:36 +0000855
Douglas Gregora376d102010-07-02 21:50:04 +0000856 // If this is the name of an implicitly-declared special member function,
857 // go through the scope stack to implicitly declare
858 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
859 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
860 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
861 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
862 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000863
Douglas Gregora376d102010-07-02 21:50:04 +0000864 // Implicitly declare member functions with the name we're looking for, if in
865 // fact we are in a scope where it matters.
866
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000867 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000868 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000869 I = IdResolver.begin(Name),
870 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000871
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000872 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000873 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000874 // ...During unqualified name lookup (3.4.1), the names appear as if
875 // they were declared in the nearest enclosing namespace which contains
876 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000877 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000878 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000879 //
880 // For example:
881 // namespace A { int i; }
882 // void foo() {
883 // int i;
884 // {
885 // using namespace A;
886 // ++i; // finds local 'i', A::i appears at global scope
887 // }
888 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000889 //
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000890 UnqualUsingDirectiveSet UDirs;
891 bool VisitedUsingDirectives = false;
Richard Smithdd9459f2013-08-13 18:18:50 +0000892 bool LeftStartingScope = false;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000893 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000894 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000895 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
896
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000897 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000898 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000899 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000900 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smithdd9459f2013-08-13 18:18:50 +0000901 if (NameKind == LookupRedeclarationWithLinkage) {
902 // Determine whether this (or a previous) declaration is
903 // out-of-scope.
904 if (!LeftStartingScope && !Initial->isDeclScope(*I))
905 LeftStartingScope = true;
906
907 // If we found something outside of our starting scope that
908 // does not have linkage, skip it.
909 if (LeftStartingScope && !((*I)->hasLinkage())) {
910 R.setShadowed();
911 continue;
912 }
913 }
914
John McCallf36e02d2009-10-09 21:13:30 +0000915 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000916 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000917 }
918 }
John McCallf36e02d2009-10-09 21:13:30 +0000919 if (Found) {
920 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000921 if (S->isClassScope())
922 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
923 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000924 return true;
925 }
926
Richard Smithdd9459f2013-08-13 18:18:50 +0000927 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith4e9686b2013-08-09 04:35:01 +0000928 // C++11 [class.friend]p11:
929 // If a friend declaration appears in a local class and the name
930 // specified is an unqualified name, a prior declaration is
931 // looked up without considering scopes that are outside the
932 // innermost enclosing non-class scope.
933 return false;
934 }
935
Douglas Gregor711be1e2010-03-15 14:33:29 +0000936 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
937 S->getParent() && !S->getParent()->isTemplateParamScope()) {
938 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000939 // found nothing, so look into the contexts between the
Douglas Gregor711be1e2010-03-15 14:33:29 +0000940 // lexical and semantic declaration contexts returned by
941 // findOuterContext(). This implements the name lookup behavior
942 // of C++ [temp.local]p8.
943 Ctx = OutsideOfTemplateParamDC;
944 OutsideOfTemplateParamDC = 0;
945 }
946
947 if (Ctx) {
948 DeclContext *OuterCtx;
949 bool SearchAfterTemplateScope;
950 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
951 if (SearchAfterTemplateScope)
952 OutsideOfTemplateParamDC = OuterCtx;
953
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000954 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000955 // We do not directly look into transparent contexts, since
956 // those entities will be found in the nearest enclosing
957 // non-transparent context.
958 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000959 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000960
961 // We do not look directly into function or method contexts,
962 // since all of the local variables and parameters of the
963 // function/method are present within the Scope.
964 if (Ctx->isFunctionOrMethod()) {
965 // If we have an Objective-C instance method, look for ivars
966 // in the corresponding interface.
967 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
968 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
969 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
970 ObjCInterfaceDecl *ClassDeclared;
971 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000972 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000973 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000974 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
975 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000976 R.resolveKind();
977 return true;
978 }
979 }
980 }
981 }
982
983 continue;
984 }
985
Douglas Gregor6bed88e2013-03-27 12:51:49 +0000986 // If this is a file context, we need to perform unqualified name
987 // lookup considering using directives.
988 if (Ctx->isFileContext()) {
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000989 // If we haven't handled using directives yet, do so now.
990 if (!VisitedUsingDirectives) {
991 // Add using directives from this context up to the top level.
Douglas Gregor34366202013-04-09 01:49:26 +0000992 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
993 if (UCtx->isTransparentContext())
994 continue;
995
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000996 UDirs.visit(UCtx, UCtx);
Douglas Gregor34366202013-04-09 01:49:26 +0000997 }
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000998
999 // Find the innermost file scope, so we can add using directives
1000 // from local scopes.
1001 Scope *InnermostFileScope = S;
1002 while (InnermostFileScope &&
1003 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1004 InnermostFileScope = InnermostFileScope->getParent();
1005 UDirs.visitScopeChain(Initial, InnermostFileScope);
1006
1007 UDirs.done();
1008
1009 VisitedUsingDirectives = true;
1010 }
Douglas Gregor6bed88e2013-03-27 12:51:49 +00001011
1012 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1013 R.resolveKind();
1014 return true;
1015 }
1016
1017 continue;
1018 }
1019
Douglas Gregore942bbe2009-09-10 16:57:35 +00001020 // Perform qualified name lookup into this context.
1021 // FIXME: In some cases, we know that every name that could be found by
1022 // this qualified name lookup will also be on the identifier chain. For
1023 // example, inside a class without any base classes, we never need to
1024 // perform qualified lookup because all of the members are on top of the
1025 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001026 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +00001027 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +00001028 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001029 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001030 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001031
John McCalld7be78a2009-11-10 07:01:13 +00001032 // Stop if we ran out of scopes.
1033 // FIXME: This really, really shouldn't be happening.
1034 if (!S) return false;
1035
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001036 // If we are looking for members, no need to look into global/namespace scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00001037 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001038 return false;
1039
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001040 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001041 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +00001042 //
Mike Stump390b4cc2009-05-16 07:39:55 +00001043 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1044 // don't build it for each lookup!
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001045 if (!VisitedUsingDirectives) {
1046 UDirs.visitScopeChain(Initial, S);
1047 UDirs.done();
1048 }
1049
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001050 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001051 // Unqualified name lookup in C++ requires looking into scopes
1052 // that aren't strictly lexical, and therefore we walk through the
1053 // context as well as walking through the scopes.
1054 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001055 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +00001056 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +00001057 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +00001058 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001059 // We found something. Look for anything else in our scope
1060 // with this same name and in an acceptable identifier
1061 // namespace, so that we can construct an overload set if we
1062 // need to.
John McCallf36e02d2009-10-09 21:13:30 +00001063 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +00001064 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001065 }
1066 }
1067
Douglas Gregor00b4b032010-05-14 04:53:42 +00001068 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +00001069 R.resolveKind();
1070 return true;
1071 }
1072
Douglas Gregor00b4b032010-05-14 04:53:42 +00001073 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1074 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1075 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1076 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001077 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001078 // lexical and semantic declaration contexts returned by
1079 // findOuterContext(). This implements the name lookup behavior
1080 // of C++ [temp.local]p8.
1081 Ctx = OutsideOfTemplateParamDC;
1082 OutsideOfTemplateParamDC = 0;
1083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001084
Douglas Gregor00b4b032010-05-14 04:53:42 +00001085 if (Ctx) {
1086 DeclContext *OuterCtx;
1087 bool SearchAfterTemplateScope;
1088 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1089 if (SearchAfterTemplateScope)
1090 OutsideOfTemplateParamDC = OuterCtx;
1091
1092 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1093 // We do not directly look into transparent contexts, since
1094 // those entities will be found in the nearest enclosing
1095 // non-transparent context.
1096 if (Ctx->isTransparentContext())
1097 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001098
Douglas Gregor00b4b032010-05-14 04:53:42 +00001099 // If we have a context, and it's not a context stashed in the
1100 // template parameter scope for an out-of-line definition, also
1101 // look into that context.
1102 if (!(Found && S && S->isTemplateParamScope())) {
1103 assert(Ctx->isFileContext() &&
1104 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001105
Douglas Gregor00b4b032010-05-14 04:53:42 +00001106 // Look into context considering using-directives.
1107 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1108 Found = true;
1109 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001110
Douglas Gregor00b4b032010-05-14 04:53:42 +00001111 if (Found) {
1112 R.resolveKind();
1113 return true;
1114 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001115
Douglas Gregor00b4b032010-05-14 04:53:42 +00001116 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1117 return false;
1118 }
1119 }
1120
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001121 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001122 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001123 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001124
John McCallf36e02d2009-10-09 21:13:30 +00001125 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001126}
1127
Richard Smithb7751002013-07-25 23:08:39 +00001128/// \brief Find the declaration that a class temploid member specialization was
1129/// instantiated from, or the member itself if it is an explicit specialization.
1130static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1131 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1132}
1133
1134/// \brief Find the module in which the given declaration was defined.
1135static Module *getDefiningModule(Decl *Entity) {
1136 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1137 // If this function was instantiated from a template, the defining module is
1138 // the module containing the pattern.
1139 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1140 Entity = Pattern;
1141 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1142 // If it's a class template specialization, find the template or partial
1143 // specialization from which it was instantiated.
1144 if (ClassTemplateSpecializationDecl *SpecRD =
1145 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1146 llvm::PointerUnion<ClassTemplateDecl*,
1147 ClassTemplatePartialSpecializationDecl*> From =
1148 SpecRD->getInstantiatedFrom();
1149 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1150 Entity = FromTemplate->getTemplatedDecl();
1151 else if (From)
1152 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1153 // Otherwise, it's an explicit specialization.
1154 } else if (MemberSpecializationInfo *MSInfo =
1155 RD->getMemberSpecializationInfo())
1156 Entity = getInstantiatedFrom(RD, MSInfo);
1157 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1158 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1159 Entity = getInstantiatedFrom(ED, MSInfo);
1160 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1161 // FIXME: Map from variable template specializations back to the template.
1162 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1163 Entity = getInstantiatedFrom(VD, MSInfo);
1164 }
1165
1166 // Walk up to the containing context. That might also have been instantiated
1167 // from a template.
1168 DeclContext *Context = Entity->getDeclContext();
1169 if (Context->isFileContext())
1170 return Entity->getOwningModule();
1171 return getDefiningModule(cast<Decl>(Context));
1172}
1173
1174llvm::DenseSet<Module*> &Sema::getLookupModules() {
1175 unsigned N = ActiveTemplateInstantiations.size();
1176 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1177 I != N; ++I) {
1178 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1179 if (M && !LookupModulesCache.insert(M).second)
1180 M = 0;
1181 ActiveTemplateInstantiationLookupModules.push_back(M);
1182 }
1183 return LookupModulesCache;
1184}
1185
1186/// \brief Determine whether a declaration is visible to name lookup.
1187///
1188/// This routine determines whether the declaration D is visible in the current
1189/// lookup context, taking into account the current template instantiation
1190/// stack. During template instantiation, a declaration is visible if it is
1191/// visible from a module containing any entity on the template instantiation
1192/// path (by instantiating a template, you allow it to see the declarations that
1193/// your module can see, including those later on in your module).
1194bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1195 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1196 "should not call this: not in slow case");
1197 Module *DeclModule = D->getOwningModule();
1198 assert(DeclModule && "hidden decl not from a module");
1199
1200 // Find the extra places where we need to look.
1201 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1202 if (LookupModules.empty())
1203 return false;
1204
1205 // If our lookup set contains the decl's module, it's visible.
1206 if (LookupModules.count(DeclModule))
1207 return true;
1208
1209 // If the declaration isn't exported, it's not visible in any other module.
1210 if (D->isModulePrivate())
1211 return false;
1212
1213 // Check whether DeclModule is transitively exported to an import of
1214 // the lookup set.
1215 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1216 E = LookupModules.end();
1217 I != E; ++I)
1218 if ((*I)->isModuleVisible(DeclModule))
1219 return true;
1220 return false;
1221}
1222
Douglas Gregor55368912011-12-14 16:03:29 +00001223/// \brief Retrieve the visible declaration corresponding to D, if any.
1224///
1225/// This routine determines whether the declaration D is visible in the current
1226/// module, with the current imports. If not, it checks whether any
1227/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smithb7751002013-07-25 23:08:39 +00001228///
Douglas Gregor55368912011-12-14 16:03:29 +00001229/// \returns D, or a visible previous declaration of D, whichever is more recent
1230/// and visible. If no declaration of D is visible, returns null.
Richard Smithd67679d2013-08-20 20:35:18 +00001231static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1232 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smithb7751002013-07-25 23:08:39 +00001233
Douglas Gregor0782ef22012-01-06 22:05:37 +00001234 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1235 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001236 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Richard Smithd67679d2013-08-20 20:35:18 +00001237 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor0782ef22012-01-06 22:05:37 +00001238 return ND;
1239 }
Douglas Gregor55368912011-12-14 16:03:29 +00001240 }
Richard Smithb7751002013-07-25 23:08:39 +00001241
Douglas Gregor55368912011-12-14 16:03:29 +00001242 return 0;
1243}
1244
Richard Smithd67679d2013-08-20 20:35:18 +00001245NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1246 return findAcceptableDecl(SemaRef, D);
1247}
1248
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001249/// @brief Perform unqualified name lookup starting from a given
1250/// scope.
1251///
1252/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1253/// used to find names within the current scope. For example, 'x' in
1254/// @code
1255/// int x;
1256/// int f() {
1257/// return x; // unqualified name look finds 'x' in the global scope
1258/// }
1259/// @endcode
1260///
1261/// Different lookup criteria can find different names. For example, a
1262/// particular scope can have both a struct and a function of the same
1263/// name, and each can be found by certain lookup criteria. For more
1264/// information about lookup criteria, see the documentation for the
1265/// class LookupCriteria.
1266///
1267/// @param S The scope from which unqualified name lookup will
1268/// begin. If the lookup criteria permits, name lookup may also search
1269/// in the parent scopes.
1270///
James Dennett8da16872012-06-22 10:32:46 +00001271/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1272/// look up and the lookup kind), and is updated with the results of lookup
1273/// including zero or more declarations and possibly additional information
1274/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001275///
James Dennett8da16872012-06-22 10:32:46 +00001276/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001277bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1278 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001279 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001280
John McCalla24dc2e2009-11-17 02:14:36 +00001281 LookupNameKind NameKind = R.getLookupKind();
1282
David Blaikie4e4d0842012-03-11 07:00:24 +00001283 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001284 // Unqualified name lookup in C/Objective-C is purely lexical, so
1285 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001286 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001287 // Find the nearest non-transparent declaration scope.
1288 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001289 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001290 static_cast<DeclContext *>(S->getEntity())
1291 ->isTransparentContext()))
1292 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001293 }
1294
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001295 // Scan up the scope chain looking for a decl that matches this
1296 // identifier that is in the appropriate namespace. This search
1297 // should not take long, as shadowing of names is uncommon, and
1298 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001299 bool LeftStartingScope = false;
1300
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001301 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001302 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001303 I != IEnd; ++I)
Richard Smithb7751002013-07-25 23:08:39 +00001304 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001305 if (NameKind == LookupRedeclarationWithLinkage) {
1306 // Determine whether this (or a previous) declaration is
1307 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001308 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001309 LeftStartingScope = true;
1310
1311 // If we found something outside of our starting scope that
1312 // does not have linkage, skip it.
Richard Smithdd9459f2013-08-13 18:18:50 +00001313 if (LeftStartingScope && !((*I)->hasLinkage())) {
1314 R.setShadowed();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001315 continue;
Richard Smithdd9459f2013-08-13 18:18:50 +00001316 }
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001317 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001318 else if (NameKind == LookupObjCImplicitSelfParam &&
1319 !isa<ImplicitParamDecl>(*I))
1320 continue;
Richard Smithb7751002013-07-25 23:08:39 +00001321
Douglas Gregor55368912011-12-14 16:03:29 +00001322 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001323
Douglas Gregor7a537402012-01-03 23:26:26 +00001324 // Check whether there are any other declarations with the same name
1325 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001326 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001327 // Find the scope in which this declaration was declared (if it
1328 // actually exists in a Scope).
1329 while (S && !S->isDeclScope(D))
1330 S = S->getParent();
1331
1332 // If the scope containing the declaration is the translation unit,
1333 // then we'll need to perform our checks based on the matching
1334 // DeclContexts rather than matching scopes.
1335 if (S && isNamespaceOrTranslationUnitScope(S))
1336 S = 0;
1337
1338 // Compute the DeclContext, if we need it.
1339 DeclContext *DC = 0;
1340 if (!S)
1341 DC = (*I)->getDeclContext()->getRedeclContext();
1342
Douglas Gregorda795b42012-01-04 16:44:10 +00001343 IdentifierResolver::iterator LastI = I;
1344 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001345 if (S) {
1346 // Match based on scope.
1347 if (!S->isDeclScope(*LastI))
1348 break;
1349 } else {
1350 // Match based on DeclContext.
1351 DeclContext *LastDC
1352 = (*LastI)->getDeclContext()->getRedeclContext();
1353 if (!LastDC->Equals(DC))
1354 break;
1355 }
Richard Smithb7751002013-07-25 23:08:39 +00001356
1357 // If the declaration is in the right namespace and visible, add it.
1358 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1359 R.addDecl(LastD);
Douglas Gregorda795b42012-01-04 16:44:10 +00001360 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001361
Douglas Gregorda795b42012-01-04 16:44:10 +00001362 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001363 }
John McCallf36e02d2009-10-09 21:13:30 +00001364 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001365 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001366 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001367 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001368 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001369 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001370 }
1371
1372 // If we didn't find a use of this identifier, and if the identifier
1373 // corresponds to a compiler builtin, create the decl object for the builtin
1374 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001375 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1376 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001377
Axel Naumannf8291a12011-02-24 16:47:47 +00001378 // If we didn't find a use of this identifier, the ExternalSource
1379 // may be able to handle the situation.
1380 // Note: some lookup failures are expected!
1381 // See e.g. R.isForRedeclaration().
1382 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001383}
1384
John McCall6e247262009-10-10 05:48:19 +00001385/// @brief Perform qualified name lookup in the namespaces nominated by
1386/// using directives by the given context.
1387///
1388/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001389/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001390/// (where X is the global namespace), let S be the set of all
1391/// declarations of m in X and in the transitive closure of all
1392/// namespaces nominated by using-directives in X and its used
1393/// namespaces, except that using-directives are ignored in any
1394/// namespace, including X, directly containing one or more
1395/// declarations of m. No namespace is searched more than once in
1396/// the lookup of a name. If S is the empty set, the program is
1397/// ill-formed. Otherwise, if S has exactly one member, or if the
1398/// context of the reference is a using-declaration
1399/// (namespace.udecl), S is the required set of declarations of
1400/// m. Otherwise if the use of m is not one that allows a unique
1401/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001402///
John McCall6e247262009-10-10 05:48:19 +00001403/// C++98 [namespace.qual]p5:
1404/// During the lookup of a qualified namespace member name, if the
1405/// lookup finds more than one declaration of the member, and if one
1406/// declaration introduces a class name or enumeration name and the
1407/// other declarations either introduce the same object, the same
1408/// enumerator or a set of functions, the non-type name hides the
1409/// class or enumeration name if and only if the declarations are
1410/// from the same namespace; otherwise (the declarations are from
1411/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001412static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001413 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001414 assert(StartDC->isFileContext() && "start context is not a file context");
1415
1416 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1417 DeclContext::udir_iterator E = StartDC->using_directives_end();
1418
1419 if (I == E) return false;
1420
1421 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001422 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001423 Visited.insert(StartDC);
1424
1425 // We have not yet looked into these namespaces, much less added
1426 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001427 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001428
1429 // We have already looked into the initial namespace; seed the queue
1430 // with its using-children.
1431 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001432 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001433 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001434 Queue.push_back(ND);
1435 }
1436
1437 // The easiest way to implement the restriction in [namespace.qual]p5
1438 // is to check whether any of the individual results found a tag
1439 // and, if so, to declare an ambiguity if the final result is not
1440 // a tag.
1441 bool FoundTag = false;
1442 bool FoundNonTag = false;
1443
John McCall7d384dd2009-11-18 07:57:50 +00001444 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001445
1446 bool Found = false;
1447 while (!Queue.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00001448 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6e247262009-10-10 05:48:19 +00001449
1450 // We go through some convolutions here to avoid copying results
1451 // between LookupResults.
1452 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001453 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001454 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001455
1456 if (FoundDirect) {
1457 // First do any local hiding.
1458 DirectR.resolveKind();
1459
1460 // If the local result is a tag, remember that.
1461 if (DirectR.isSingleTagDecl())
1462 FoundTag = true;
1463 else
1464 FoundNonTag = true;
1465
1466 // Append the local results to the total results if necessary.
1467 if (UseLocal) {
1468 R.addAllDecls(LocalR);
1469 LocalR.clear();
1470 }
1471 }
1472
1473 // If we find names in this namespace, ignore its using directives.
1474 if (FoundDirect) {
1475 Found = true;
1476 continue;
1477 }
1478
1479 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1480 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001481 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001482 Queue.push_back(Nom);
1483 }
1484 }
1485
1486 if (Found) {
1487 if (FoundTag && FoundNonTag)
1488 R.setAmbiguousQualifiedTagHiding();
1489 else
1490 R.resolveKind();
1491 }
1492
1493 return Found;
1494}
1495
Douglas Gregor8071e422010-08-15 06:18:01 +00001496/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001497static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001498 CXXBasePath &Path,
1499 void *Name) {
1500 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001501
Douglas Gregor8071e422010-08-15 06:18:01 +00001502 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1503 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001504 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001505}
1506
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001507/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001508/// static members, nested types, and enumerators.
1509template<typename InputIterator>
1510static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1511 Decl *D = (*First)->getUnderlyingDecl();
1512 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1513 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001514
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001515 if (isa<CXXMethodDecl>(D)) {
1516 // Determine whether all of the methods are static.
1517 bool AllMethodsAreStatic = true;
1518 for(; First != Last; ++First) {
1519 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001520
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001521 if (!isa<CXXMethodDecl>(D)) {
1522 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1523 break;
1524 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001525
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001526 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1527 AllMethodsAreStatic = false;
1528 break;
1529 }
1530 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001531
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001532 if (AllMethodsAreStatic)
1533 return true;
1534 }
1535
1536 return false;
1537}
1538
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001539/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001540///
1541/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1542/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001543/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001544///
1545/// Different lookup criteria can find different names. For example, a
1546/// particular scope can have both a struct and a function of the same
1547/// name, and each can be found by certain lookup criteria. For more
1548/// information about lookup criteria, see the documentation for the
1549/// class LookupCriteria.
1550///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001551/// \param R captures both the lookup criteria and any lookup results found.
1552///
1553/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001554/// search. If the lookup criteria permits, name lookup may also search
1555/// in the parent contexts or (for C++ classes) base classes.
1556///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001557/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001558/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001559///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001560/// \returns true if lookup succeeded, false if it failed.
1561bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1562 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001563 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001564
John McCalla24dc2e2009-11-17 02:14:36 +00001565 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001566 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001568 // Make sure that the declaration context is complete.
1569 assert((!isa<TagDecl>(LookupCtx) ||
1570 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001571 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001572 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001573 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001575 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001576 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001577 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001578 if (isa<CXXRecordDecl>(LookupCtx))
1579 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001580 return true;
1581 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001582
John McCall6e247262009-10-10 05:48:19 +00001583 // Don't descend into implied contexts for redeclarations.
1584 // C++98 [namespace.qual]p6:
1585 // In a declaration for a namespace member in which the
1586 // declarator-id is a qualified-id, given that the qualified-id
1587 // for the namespace member has the form
1588 // nested-name-specifier unqualified-id
1589 // the unqualified-id shall name a member of the namespace
1590 // designated by the nested-name-specifier.
1591 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001592 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001593 return false;
1594
John McCalla24dc2e2009-11-17 02:14:36 +00001595 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001596 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001597 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001598
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001599 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001600 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001601 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001602 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001603 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001604
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001605 // If we're performing qualified name lookup into a dependent class,
1606 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001607 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001608 // template instantiation time (at which point all bases will be available)
1609 // or we have to fail.
1610 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1611 LookupRec->hasAnyDependentBases()) {
1612 R.setNotFoundInCurrentInstantiation();
1613 return false;
1614 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001615
Douglas Gregor7176fff2009-01-15 00:26:24 +00001616 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001617 CXXBasePaths Paths;
1618 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001619
1620 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001621 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001622 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001623 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001624 case LookupOrdinaryName:
1625 case LookupMemberName:
1626 case LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +00001627 case LookupLocalFriendName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001628 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1629 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001630
Douglas Gregora8f32e02009-10-06 17:59:45 +00001631 case LookupTagName:
1632 BaseCallback = &CXXRecordDecl::FindTagMember;
1633 break;
John McCall9f54ad42009-12-10 09:41:52 +00001634
Douglas Gregor8071e422010-08-15 06:18:01 +00001635 case LookupAnyName:
1636 BaseCallback = &LookupAnyMember;
1637 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001638
John McCall9f54ad42009-12-10 09:41:52 +00001639 case LookupUsingDeclName:
1640 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001641
Douglas Gregora8f32e02009-10-06 17:59:45 +00001642 case LookupOperatorName:
1643 case LookupNamespaceName:
1644 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001645 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001646 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001647 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001648
Douglas Gregora8f32e02009-10-06 17:59:45 +00001649 case LookupNestedNameSpecifierName:
1650 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1651 break;
1652 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001653
John McCalla24dc2e2009-11-17 02:14:36 +00001654 if (!LookupRec->lookupInBases(BaseCallback,
1655 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001656 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001657
John McCall92f88312010-01-23 00:46:32 +00001658 R.setNamingClass(LookupRec);
1659
Douglas Gregor7176fff2009-01-15 00:26:24 +00001660 // C++ [class.member.lookup]p2:
1661 // [...] If the resulting set of declarations are not all from
1662 // sub-objects of the same type, or the set has a nonstatic member
1663 // and includes members from distinct sub-objects, there is an
1664 // ambiguity and the program is ill-formed. Otherwise that set is
1665 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001666 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001667 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001668 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001669
Douglas Gregora8f32e02009-10-06 17:59:45 +00001670 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001671 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001672 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001673
John McCall46460a62010-01-20 21:53:11 +00001674 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1675 // across all paths.
1676 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677
Douglas Gregor7176fff2009-01-15 00:26:24 +00001678 // Determine whether we're looking at a distinct sub-object or not.
1679 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001680 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001681 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1682 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001683 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001684 }
1685
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001686 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001687 != Context.getCanonicalType(PathElement.Base->getType())) {
1688 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001689 // different types. If the declaration sets aren't the same, this
1690 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001691 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001692 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001693 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1694 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001695
David Blaikie3bc93e32012-12-19 00:45:41 +00001696 while (FirstD != FirstPath->Decls.end() &&
1697 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001698 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1699 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1700 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001701
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001702 ++FirstD;
1703 ++CurrentD;
1704 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001705
David Blaikie3bc93e32012-12-19 00:45:41 +00001706 if (FirstD == FirstPath->Decls.end() &&
1707 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001708 continue;
1709 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001710
John McCallf36e02d2009-10-09 21:13:30 +00001711 R.setAmbiguousBaseSubobjectTypes(Paths);
1712 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001713 }
1714
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001715 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001716 // We have a different subobject of the same type.
1717
1718 // C++ [class.member.lookup]p5:
1719 // A static member, a nested type or an enumerator defined in
1720 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001721 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001722 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001723 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001724
Douglas Gregor7176fff2009-01-15 00:26:24 +00001725 // We have found a nonstatic member name in multiple, distinct
1726 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001727 R.setAmbiguousBaseSubobjects(Paths);
1728 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001729 }
1730 }
1731
1732 // Lookup in a base class succeeded; return these results.
1733
David Blaikie3bc93e32012-12-19 00:45:41 +00001734 DeclContext::lookup_result DR = Paths.front().Decls;
1735 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001736 NamedDecl *D = *I;
1737 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1738 D->getAccess());
1739 R.addDecl(D, AS);
1740 }
John McCallf36e02d2009-10-09 21:13:30 +00001741 R.resolveKind();
1742 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001743}
1744
1745/// @brief Performs name lookup for a name that was parsed in the
1746/// source code, and may contain a C++ scope specifier.
1747///
1748/// This routine is a convenience routine meant to be called from
1749/// contexts that receive a name and an optional C++ scope specifier
1750/// (e.g., "N::M::x"). It will then perform either qualified or
1751/// unqualified name lookup (with LookupQualifiedName or LookupName,
1752/// respectively) on the given name and return those results.
1753///
1754/// @param S The scope from which unqualified name lookup will
1755/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001756///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001757/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001758///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001759/// @param EnteringContext Indicates whether we are going to enter the
1760/// context of the scope-specifier SS (if present).
1761///
John McCallf36e02d2009-10-09 21:13:30 +00001762/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001763bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001764 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001765 if (SS && SS->isInvalid()) {
1766 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001767 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001768 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001769 }
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Douglas Gregor495c35d2009-08-25 22:51:20 +00001771 if (SS && SS->isSet()) {
1772 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001773 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001774 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001775 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001776 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001777
John McCalla24dc2e2009-11-17 02:14:36 +00001778 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001779 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001780 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001781
Douglas Gregor495c35d2009-08-25 22:51:20 +00001782 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001783 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001784 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001785 R.setNotFoundInCurrentInstantiation();
1786 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001787 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001788 }
1789
Mike Stump1eb44332009-09-09 15:08:12 +00001790 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001791 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001792}
1793
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001794
James Dennett16ae9de2012-06-22 10:16:05 +00001795/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001796/// from name lookup.
1797///
James Dennett16ae9de2012-06-22 10:16:05 +00001798/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001799void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001800 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1801
John McCalla24dc2e2009-11-17 02:14:36 +00001802 DeclarationName Name = Result.getLookupName();
1803 SourceLocation NameLoc = Result.getNameLoc();
1804 SourceRange LookupRange = Result.getContextRange();
1805
John McCall6e247262009-10-10 05:48:19 +00001806 switch (Result.getAmbiguityKind()) {
1807 case LookupResult::AmbiguousBaseSubobjects: {
1808 CXXBasePaths *Paths = Result.getBasePaths();
1809 QualType SubobjectType = Paths->front().back().Base->getType();
1810 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1811 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1812 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001813
David Blaikie3bc93e32012-12-19 00:45:41 +00001814 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001815 while (isa<CXXMethodDecl>(*Found) &&
1816 cast<CXXMethodDecl>(*Found)->isStatic())
1817 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001818
John McCall6e247262009-10-10 05:48:19 +00001819 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001820 break;
John McCall6e247262009-10-10 05:48:19 +00001821 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001822
John McCall6e247262009-10-10 05:48:19 +00001823 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001824 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1825 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001826
John McCall6e247262009-10-10 05:48:19 +00001827 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001828 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001829 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1830 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001831 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001832 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001833 if (DeclsPrinted.insert(D).second)
1834 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1835 }
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001836 break;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001837 }
1838
John McCall6e247262009-10-10 05:48:19 +00001839 case LookupResult::AmbiguousTagHiding: {
1840 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001841
John McCall6e247262009-10-10 05:48:19 +00001842 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1843
1844 LookupResult::iterator DI, DE = Result.end();
1845 for (DI = Result.begin(); DI != DE; ++DI)
1846 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1847 TagDecls.insert(TD);
1848 Diag(TD->getLocation(), diag::note_hidden_tag);
1849 }
1850
1851 for (DI = Result.begin(); DI != DE; ++DI)
1852 if (!isa<TagDecl>(*DI))
1853 Diag((*DI)->getLocation(), diag::note_hiding_object);
1854
1855 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001856 LookupResult::Filter F = Result.makeFilter();
1857 while (F.hasNext()) {
1858 if (TagDecls.count(F.next()))
1859 F.erase();
1860 }
1861 F.done();
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001862 break;
John McCall6e247262009-10-10 05:48:19 +00001863 }
1864
1865 case LookupResult::AmbiguousReference: {
1866 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001867
John McCall6e247262009-10-10 05:48:19 +00001868 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1869 for (; DI != DE; ++DI)
1870 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001871 break;
John McCall6e247262009-10-10 05:48:19 +00001872 }
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001873 }
Douglas Gregor7176fff2009-01-15 00:26:24 +00001874}
Douglas Gregorfa047642009-02-04 00:32:51 +00001875
John McCallc7e04da2010-05-28 18:45:08 +00001876namespace {
1877 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001878 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001879 Sema::AssociatedNamespaceSet &Namespaces,
1880 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001881 : S(S), Namespaces(Namespaces), Classes(Classes),
1882 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001883 }
1884
1885 Sema &S;
1886 Sema::AssociatedNamespaceSet &Namespaces;
1887 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001888 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001889 };
1890}
1891
Mike Stump1eb44332009-09-09 15:08:12 +00001892static void
John McCallc7e04da2010-05-28 18:45:08 +00001893addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001894
Douglas Gregor54022952010-04-30 07:08:38 +00001895static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1896 DeclContext *Ctx) {
1897 // Add the associated namespace for this class.
1898
1899 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1900 // be a locally scoped record.
1901
Sebastian Redl410c4f22010-08-31 20:53:31 +00001902 // We skip out of inline namespaces. The innermost non-inline namespace
1903 // contains all names of all its nested inline namespaces anyway, so we can
1904 // replace the entire inline namespace tree with its root.
1905 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1906 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001907 Ctx = Ctx->getParent();
1908
John McCall6ff07852009-08-07 22:18:02 +00001909 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001910 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001911}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001912
Mike Stump1eb44332009-09-09 15:08:12 +00001913// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001914// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001915static void
John McCallc7e04da2010-05-28 18:45:08 +00001916addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1917 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001918 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001919 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001920 switch (Arg.getKind()) {
1921 case TemplateArgument::Null:
1922 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Douglas Gregor69be8d62009-07-08 07:51:57 +00001924 case TemplateArgument::Type:
1925 // [...] the namespaces and classes associated with the types of the
1926 // template arguments provided for template type parameters (excluding
1927 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001928 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001929 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001930
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001931 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001932 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001933 // [...] the namespaces in which any template template arguments are
1934 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001935 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001936 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001937 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001938 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001939 DeclContext *Ctx = ClassTemplate->getDeclContext();
1940 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001941 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001942 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001943 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001944 }
1945 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001946 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001947
Douglas Gregor788cd062009-11-11 01:00:40 +00001948 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001949 case TemplateArgument::Integral:
1950 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001951 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001952 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001953 // associated namespaces. ]
1954 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Douglas Gregor69be8d62009-07-08 07:51:57 +00001956 case TemplateArgument::Pack:
1957 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1958 PEnd = Arg.pack_end();
1959 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001960 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001961 break;
1962 }
1963}
1964
Douglas Gregorfa047642009-02-04 00:32:51 +00001965// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001966// argument-dependent lookup with an argument of class type
1967// (C++ [basic.lookup.koenig]p2).
1968static void
John McCallc7e04da2010-05-28 18:45:08 +00001969addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1970 CXXRecordDecl *Class) {
1971
1972 // Just silently ignore anything whose name is __va_list_tag.
1973 if (Class->getDeclName() == Result.S.VAListTagName)
1974 return;
1975
Douglas Gregorfa047642009-02-04 00:32:51 +00001976 // C++ [basic.lookup.koenig]p2:
1977 // [...]
1978 // -- If T is a class type (including unions), its associated
1979 // classes are: the class itself; the class of which it is a
1980 // member, if any; and its direct and indirect base
1981 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001982 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001983
1984 // Add the class of which it is a member, if any.
1985 DeclContext *Ctx = Class->getDeclContext();
1986 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001987 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001988 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001989 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Douglas Gregorfa047642009-02-04 00:32:51 +00001991 // Add the class itself. If we've already seen this class, we don't
1992 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001993 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001994 return;
1995
Mike Stump1eb44332009-09-09 15:08:12 +00001996 // -- If T is a template-id, its associated namespaces and classes are
1997 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001998 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001999 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00002000 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00002001 // namespaces in which any template template arguments are defined; and
2002 // the classes in which any member templates used as template template
2003 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00002004 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00002005 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00002006 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2007 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2008 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002009 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002010 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002011 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Douglas Gregor69be8d62009-07-08 07:51:57 +00002013 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2014 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00002015 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002016 }
Mike Stump1eb44332009-09-09 15:08:12 +00002017
John McCall86ff3082010-02-04 22:26:26 +00002018 // Only recurse into base classes for complete types.
2019 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00002020 QualType type = Result.S.Context.getTypeDeclType(Class);
2021 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
2022 /*no diagnostic*/ 0))
2023 return;
John McCall86ff3082010-02-04 22:26:26 +00002024 }
2025
Douglas Gregorfa047642009-02-04 00:32:51 +00002026 // Add direct and indirect base classes along with their associated
2027 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002028 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00002029 Bases.push_back(Class);
2030 while (!Bases.empty()) {
2031 // Pop this class off the stack.
Robert Wilhelm344472e2013-08-23 16:11:15 +00002032 Class = Bases.pop_back_val();
Douglas Gregorfa047642009-02-04 00:32:51 +00002033
2034 // Visit the base classes.
2035 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
2036 BaseEnd = Class->bases_end();
2037 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002038 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00002039 // In dependent contexts, we do ADL twice, and the first time around,
2040 // the base type might be a dependent TemplateSpecializationType, or a
2041 // TemplateTypeParmType. If that happens, simply ignore it.
2042 // FIXME: If we want to support export, we probably need to add the
2043 // namespace of the template in a TemplateSpecializationType, or even
2044 // the classes and namespaces of known non-dependent arguments.
2045 if (!BaseType)
2046 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002047 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002048 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002049 // Find the associated namespace for this base class.
2050 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00002051 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002052
2053 // Make sure we visit the bases of this base class.
2054 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2055 Bases.push_back(BaseDecl);
2056 }
2057 }
2058 }
2059}
2060
2061// \brief Add the associated classes and namespaces for
2062// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00002063// (C++ [basic.lookup.koenig]p2).
2064static void
John McCallc7e04da2010-05-28 18:45:08 +00002065addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002066 // C++ [basic.lookup.koenig]p2:
2067 //
2068 // For each argument type T in the function call, there is a set
2069 // of zero or more associated namespaces and a set of zero or more
2070 // associated classes to be considered. The sets of namespaces and
2071 // classes is determined entirely by the types of the function
2072 // arguments (and the namespace of any template template
2073 // argument). Typedef names and using-declarations used to specify
2074 // the types do not contribute to this set. The sets of namespaces
2075 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00002076
Chris Lattner5f9e2722011-07-23 10:55:15 +00002077 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00002078 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2079
Douglas Gregorfa047642009-02-04 00:32:51 +00002080 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00002081 switch (T->getTypeClass()) {
2082
2083#define TYPE(Class, Base)
2084#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2085#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2086#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2087#define ABSTRACT_TYPE(Class, Base)
2088#include "clang/AST/TypeNodes.def"
2089 // T is canonical. We can also ignore dependent types because
2090 // we don't need to do ADL at the definition point, but if we
2091 // wanted to implement template export (or if we find some other
2092 // use for associated classes and namespaces...) this would be
2093 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00002094 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002095
John McCallfa4edcf2010-05-28 06:08:54 +00002096 // -- If T is a pointer to U or an array of U, its associated
2097 // namespaces and classes are those associated with U.
2098 case Type::Pointer:
2099 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2100 continue;
2101 case Type::ConstantArray:
2102 case Type::IncompleteArray:
2103 case Type::VariableArray:
2104 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2105 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002106
John McCallfa4edcf2010-05-28 06:08:54 +00002107 // -- If T is a fundamental type, its associated sets of
2108 // namespaces and classes are both empty.
2109 case Type::Builtin:
2110 break;
2111
2112 // -- If T is a class type (including unions), its associated
2113 // classes are: the class itself; the class of which it is a
2114 // member, if any; and its direct and indirect base
2115 // classes. Its associated namespaces are the namespaces in
2116 // which its associated classes are defined.
2117 case Type::Record: {
2118 CXXRecordDecl *Class
2119 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002120 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00002121 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002122 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00002123
John McCallfa4edcf2010-05-28 06:08:54 +00002124 // -- If T is an enumeration type, its associated namespace is
2125 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002126 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00002127 // it has no associated class.
2128 case Type::Enum: {
2129 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002130
John McCallfa4edcf2010-05-28 06:08:54 +00002131 DeclContext *Ctx = Enum->getDeclContext();
2132 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002133 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002134
John McCallfa4edcf2010-05-28 06:08:54 +00002135 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002136 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002137
John McCallfa4edcf2010-05-28 06:08:54 +00002138 break;
2139 }
2140
2141 // -- If T is a function type, its associated namespaces and
2142 // classes are those associated with the function parameter
2143 // types and those associated with the return type.
2144 case Type::FunctionProto: {
2145 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2146 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2147 ArgEnd = Proto->arg_type_end();
2148 Arg != ArgEnd; ++Arg)
2149 Queue.push_back(Arg->getTypePtr());
2150 // fallthrough
2151 }
2152 case Type::FunctionNoProto: {
2153 const FunctionType *FnType = cast<FunctionType>(T);
2154 T = FnType->getResultType().getTypePtr();
2155 continue;
2156 }
2157
2158 // -- If T is a pointer to a member function of a class X, its
2159 // associated namespaces and classes are those associated
2160 // with the function parameter types and return type,
2161 // together with those associated with X.
2162 //
2163 // -- If T is a pointer to a data member of class X, its
2164 // associated namespaces and classes are those associated
2165 // with the member type together with those associated with
2166 // X.
2167 case Type::MemberPointer: {
2168 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2169
2170 // Queue up the class type into which this points.
2171 Queue.push_back(MemberPtr->getClass());
2172
2173 // And directly continue with the pointee type.
2174 T = MemberPtr->getPointeeType().getTypePtr();
2175 continue;
2176 }
2177
2178 // As an extension, treat this like a normal pointer.
2179 case Type::BlockPointer:
2180 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2181 continue;
2182
2183 // References aren't covered by the standard, but that's such an
2184 // obvious defect that we cover them anyway.
2185 case Type::LValueReference:
2186 case Type::RValueReference:
2187 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2188 continue;
2189
2190 // These are fundamental types.
2191 case Type::Vector:
2192 case Type::ExtVector:
2193 case Type::Complex:
2194 break;
2195
Richard Smithdc7a4f52013-04-30 13:56:41 +00002196 // Non-deduced auto types only get here for error cases.
2197 case Type::Auto:
2198 break;
2199
Douglas Gregorf25760e2011-04-12 01:02:45 +00002200 // If T is an Objective-C object or interface type, or a pointer to an
2201 // object or interface type, the associated namespace is the global
2202 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002203 case Type::ObjCObject:
2204 case Type::ObjCInterface:
2205 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002206 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002207 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002208
2209 // Atomic types are just wrappers; use the associations of the
2210 // contained type.
2211 case Type::Atomic:
2212 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2213 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002214 }
2215
Robert Wilhelm344472e2013-08-23 16:11:15 +00002216 if (Queue.empty())
2217 break;
2218 T = Queue.pop_back_val();
Douglas Gregorfa047642009-02-04 00:32:51 +00002219 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002220}
2221
2222/// \brief Find the associated classes and namespaces for
2223/// argument-dependent lookup for a call with the given set of
2224/// arguments.
2225///
2226/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002227/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002228/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm834c0582013-08-09 18:02:13 +00002229void Sema::FindAssociatedClassesAndNamespaces(
2230 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2231 AssociatedNamespaceSet &AssociatedNamespaces,
2232 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002233 AssociatedNamespaces.clear();
2234 AssociatedClasses.clear();
2235
John McCall42f48fb2012-08-24 20:38:34 +00002236 AssociatedLookup Result(*this, InstantiationLoc,
2237 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002238
Douglas Gregorfa047642009-02-04 00:32:51 +00002239 // C++ [basic.lookup.koenig]p2:
2240 // For each argument type T in the function call, there is a set
2241 // of zero or more associated namespaces and a set of zero or more
2242 // associated classes to be considered. The sets of namespaces and
2243 // classes is determined entirely by the types of the function
2244 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002245 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002246 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002247 Expr *Arg = Args[ArgIdx];
2248
2249 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002250 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002251 continue;
2252 }
2253
2254 // [...] In addition, if the argument is the name or address of a
2255 // set of overloaded functions and/or function templates, its
2256 // associated classes and namespaces are the union of those
2257 // associated with each of the members of the set: the namespace
2258 // in which the function or function template is defined and the
2259 // classes and namespaces associated with its (non-dependent)
2260 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002261 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002262 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002263 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002264 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002265
John McCallc7e04da2010-05-28 18:45:08 +00002266 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2267 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002268
John McCallc7e04da2010-05-28 18:45:08 +00002269 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2270 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002271 // Look through any using declarations to find the underlying function.
2272 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002273
Chandler Carruthbd647292009-12-29 06:17:27 +00002274 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2275 if (!FDecl)
2276 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002277
2278 // Add the classes and namespaces associated with the parameter
2279 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002280 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002281 }
2282 }
2283}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002284
2285/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2286/// an acceptable non-member overloaded operator for a call whose
2287/// arguments have types T1 (and, if non-empty, T2). This routine
2288/// implements the check in C++ [over.match.oper]p3b2 concerning
2289/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002290static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002291IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2292 QualType T1, QualType T2,
2293 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002294 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2295 return true;
2296
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002297 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2298 return true;
2299
John McCall183700f2009-09-21 23:43:11 +00002300 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002301 if (Proto->getNumArgs() < 1)
2302 return false;
2303
2304 if (T1->isEnumeralType()) {
2305 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002306 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002307 return true;
2308 }
2309
2310 if (Proto->getNumArgs() < 2)
2311 return false;
2312
2313 if (!T2.isNull() && T2->isEnumeralType()) {
2314 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002315 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002316 return true;
2317 }
2318
2319 return false;
2320}
2321
John McCall7d384dd2009-11-18 07:57:50 +00002322NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002323 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002324 LookupNameKind NameKind,
2325 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002326 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002327 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002328 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002329}
2330
Douglas Gregor6e378de2009-04-23 23:18:26 +00002331/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002332ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002333 SourceLocation IdLoc,
2334 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002335 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002336 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002337 return cast_or_null<ObjCProtocolDecl>(D);
2338}
2339
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002340void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002341 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002342 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002343 // C++ [over.match.oper]p3:
2344 // -- The set of non-member candidates is the result of the
2345 // unqualified lookup of operator@ in the context of the
2346 // expression according to the usual rules for name lookup in
2347 // unqualified function calls (3.4.2) except that all member
2348 // functions are ignored. However, if no operand has a class
2349 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002350 // that have a first parameter of type T1 or "reference to
2351 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002352 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002353 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002354 // when T2 is an enumeration type, are candidate functions.
2355 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002356 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2357 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002359 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2360
John McCallf36e02d2009-10-09 21:13:30 +00002361 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002362 return;
2363
2364 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2365 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002366 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2367 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002368 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002369 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002370 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002371 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002372 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002373 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002374 // later?
2375 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002376 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002377 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002378 }
2379}
2380
Sean Huntc39b6bc2011-06-24 02:11:39 +00002381Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002382 CXXSpecialMember SM,
2383 bool ConstArg,
2384 bool VolatileArg,
2385 bool RValueThis,
2386 bool ConstThis,
2387 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002388 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002389 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002390 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002391 if (RValueThis || ConstThis || VolatileThis)
2392 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2393 "constructors and destructors always have unqualified lvalue this");
2394 if (ConstArg || VolatileArg)
2395 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2396 "parameter-less special members can't have qualified arguments");
2397
2398 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002399 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002400 ID.AddInteger(SM);
2401 ID.AddInteger(ConstArg);
2402 ID.AddInteger(VolatileArg);
2403 ID.AddInteger(RValueThis);
2404 ID.AddInteger(ConstThis);
2405 ID.AddInteger(VolatileThis);
2406
2407 void *InsertPoint;
2408 SpecialMemberOverloadResult *Result =
2409 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2410
2411 // This was already cached
2412 if (Result)
2413 return Result;
2414
Sean Hunt30543582011-06-07 00:11:58 +00002415 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2416 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002417 SpecialMemberCache.InsertNode(Result, InsertPoint);
2418
2419 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002420 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002421 DeclareImplicitDestructor(RD);
2422 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002423 assert(DD && "record without a destructor");
2424 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002425 Result->setKind(DD->isDeleted() ?
2426 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002427 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002428 return Result;
2429 }
2430
Sean Huntb320e0c2011-06-10 03:50:41 +00002431 // Prepare for overload resolution. Here we construct a synthetic argument
2432 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002433 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002434 DeclarationName Name;
2435 Expr *Arg = 0;
2436 unsigned NumArgs;
2437
Richard Smith704c8f72012-04-20 18:46:14 +00002438 QualType ArgType = CanTy;
2439 ExprValueKind VK = VK_LValue;
2440
Sean Huntb320e0c2011-06-10 03:50:41 +00002441 if (SM == CXXDefaultConstructor) {
2442 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2443 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002444 if (RD->needsImplicitDefaultConstructor())
2445 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002446 } else {
2447 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2448 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002449 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002450 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002451 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002452 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002453 } else {
2454 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002455 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002456 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002457 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002458 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002459 }
2460
Sean Huntb320e0c2011-06-10 03:50:41 +00002461 if (ConstArg)
2462 ArgType.addConst();
2463 if (VolatileArg)
2464 ArgType.addVolatile();
2465
2466 // This isn't /really/ specified by the standard, but it's implied
2467 // we should be working from an RValue in the case of move to ensure
2468 // that we prefer to bind to rvalue references, and an LValue in the
2469 // case of copy to ensure we don't bind to rvalue references.
2470 // Possibly an XValue is actually correct in the case of move, but
2471 // there is no semantic difference for class types in this restricted
2472 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002473 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002474 VK = VK_LValue;
2475 else
2476 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002477 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002478
Richard Smith704c8f72012-04-20 18:46:14 +00002479 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2480
2481 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002482 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002483 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002484 }
2485
2486 // Create the object argument
2487 QualType ThisTy = CanTy;
2488 if (ConstThis)
2489 ThisTy.addConst();
2490 if (VolatileThis)
2491 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002492 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002493 OpaqueValueExpr(SourceLocation(), ThisTy,
2494 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002495
2496 // Now we perform lookup on the name we computed earlier and do overload
2497 // resolution. Lookup is only performed directly into the class since there
2498 // will always be a (possibly implicit) declaration to shadow any others.
2499 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002500 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00002501 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002502 "lookup for a constructor or assignment operator was empty");
Chandler Carruthab4e0c02013-08-18 07:20:52 +00002503
2504 // Copy the candidates as our processing of them may load new declarations
2505 // from an external source and invalidate lookup_result.
2506 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2507
2508 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithb60fae52013-09-09 16:55:27 +00002509 E = Candidates.end();
Chandler Carruthab4e0c02013-08-18 07:20:52 +00002510 I != E; ++I) {
2511 NamedDecl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002512
Sean Huntc39b6bc2011-06-24 02:11:39 +00002513 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002514 continue;
2515
Sean Huntc39b6bc2011-06-24 02:11:39 +00002516 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2517 // FIXME: [namespace.udecl]p15 says that we should only consider a
2518 // using declaration here if it does not match a declaration in the
2519 // derived class. We do not implement this correctly in other cases
2520 // either.
2521 Cand = U->getTargetDecl();
2522
2523 if (Cand->isInvalidDecl())
2524 continue;
2525 }
2526
2527 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002528 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002529 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002530 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2531 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002532 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002533 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2534 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002535 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002536 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002537 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2538 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002539 RD, 0, ThisTy, Classification,
2540 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002541 OCS, true);
2542 else
2543 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002544 0, llvm::makeArrayRef(&Arg, NumArgs),
2545 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002546 } else {
2547 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002548 }
2549 }
2550
2551 OverloadCandidateSet::iterator Best;
2552 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2553 case OR_Success:
2554 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002555 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002556 break;
2557
2558 case OR_Deleted:
2559 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002560 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002561 break;
2562
2563 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002564 Result->setMethod(0);
2565 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2566 break;
2567
Sean Huntb320e0c2011-06-10 03:50:41 +00002568 case OR_No_Viable_Function:
2569 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002570 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002571 break;
2572 }
2573
2574 return Result;
2575}
2576
2577/// \brief Look up the default constructor for the given class.
2578CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002579 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002580 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2581 false, false);
2582
2583 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002584}
2585
Sean Hunt661c67a2011-06-21 23:42:56 +00002586/// \brief Look up the copying constructor for the given class.
2587CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002588 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002589 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2590 "non-const, non-volatile qualifiers for copy ctor arg");
2591 SpecialMemberOverloadResult *Result =
2592 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2593 Quals & Qualifiers::Volatile, false, false, false);
2594
Sean Huntc530d172011-06-10 04:44:37 +00002595 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2596}
2597
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002598/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002599CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2600 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002601 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002602 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2603 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002604
2605 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2606}
2607
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002608/// \brief Look up the constructors for the given class.
2609DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002610 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002611 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002612 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002613 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002614 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002615 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002616 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002617 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002618 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002619
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002620 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2621 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2622 return Class->lookup(Name);
2623}
2624
Sean Hunt661c67a2011-06-21 23:42:56 +00002625/// \brief Look up the copying assignment operator for the given class.
2626CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2627 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002628 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002629 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2630 "non-const, non-volatile qualifiers for copy assignment arg");
2631 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2632 "non-const, non-volatile qualifiers for copy assignment this");
2633 SpecialMemberOverloadResult *Result =
2634 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2635 Quals & Qualifiers::Volatile, RValueThis,
2636 ThisQuals & Qualifiers::Const,
2637 ThisQuals & Qualifiers::Volatile);
2638
Sean Hunt661c67a2011-06-21 23:42:56 +00002639 return Result->getMethod();
2640}
2641
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002642/// \brief Look up the moving assignment operator for the given class.
2643CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002644 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002645 bool RValueThis,
2646 unsigned ThisQuals) {
2647 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2648 "non-const, non-volatile qualifiers for copy assignment this");
2649 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002650 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2651 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002652 ThisQuals & Qualifiers::Const,
2653 ThisQuals & Qualifiers::Volatile);
2654
2655 return Result->getMethod();
2656}
2657
Douglas Gregordb89f282010-07-01 22:47:18 +00002658/// \brief Look for the destructor of the given class.
2659///
Sean Huntc5c9b532011-06-03 21:10:40 +00002660/// During semantic analysis, this routine should be used in lieu of
2661/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002662///
2663/// \returns The destructor for this class.
2664CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002665 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2666 false, false, false,
2667 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002668}
2669
Richard Smith36f5cfe2012-03-09 08:00:36 +00002670/// LookupLiteralOperator - Determine which literal operator should be used for
2671/// a user-defined literal, per C++11 [lex.ext].
2672///
2673/// Normal overload resolution is not used to select which literal operator to
2674/// call for a user-defined literal. Look up the provided literal operator name,
2675/// and filter the results to the appropriate set for the given argument types.
2676Sema::LiteralOperatorLookupResult
2677Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2678 ArrayRef<QualType> ArgTys,
2679 bool AllowRawAndTemplate) {
2680 LookupName(R, S);
2681 assert(R.getResultKind() != LookupResult::Ambiguous &&
2682 "literal operator lookup can't be ambiguous");
2683
2684 // Filter the lookup results appropriately.
2685 LookupResult::Filter F = R.makeFilter();
2686
2687 bool FoundTemplate = false;
2688 bool FoundRaw = false;
2689 bool FoundExactMatch = false;
2690
2691 while (F.hasNext()) {
2692 Decl *D = F.next();
2693 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2694 D = USD->getTargetDecl();
2695
2696 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2697 bool IsRaw = false;
2698 bool IsExactMatch = false;
2699
Douglas Gregor7e0c2272013-04-10 05:18:00 +00002700 // If the declaration we found is invalid, skip it.
2701 if (D->isInvalidDecl()) {
2702 F.erase();
2703 continue;
2704 }
2705
Richard Smith36f5cfe2012-03-09 08:00:36 +00002706 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2707 if (FD->getNumParams() == 1 &&
2708 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2709 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002710 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002711 IsExactMatch = true;
2712 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2713 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2714 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2715 IsExactMatch = false;
2716 break;
2717 }
2718 }
2719 }
2720 }
2721
2722 if (IsExactMatch) {
2723 FoundExactMatch = true;
2724 AllowRawAndTemplate = false;
2725 if (FoundRaw || FoundTemplate) {
2726 // Go through again and remove the raw and template decls we've
2727 // already found.
2728 F.restart();
2729 FoundRaw = FoundTemplate = false;
2730 }
2731 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2732 FoundTemplate |= IsTemplate;
2733 FoundRaw |= IsRaw;
2734 } else {
2735 F.erase();
2736 }
2737 }
2738
2739 F.done();
2740
2741 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2742 // parameter type, that is used in preference to a raw literal operator
2743 // or literal operator template.
2744 if (FoundExactMatch)
2745 return LOLR_Cooked;
2746
2747 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2748 // operator template, but not both.
2749 if (FoundRaw && FoundTemplate) {
2750 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2751 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2752 Decl *D = *I;
2753 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2754 D = USD->getTargetDecl();
2755 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2756 D = FunTmpl->getTemplatedDecl();
2757 NoteOverloadCandidate(cast<FunctionDecl>(D));
2758 }
2759 return LOLR_Error;
2760 }
2761
2762 if (FoundRaw)
2763 return LOLR_Raw;
2764
2765 if (FoundTemplate)
2766 return LOLR_Template;
2767
2768 // Didn't find anything we could use.
2769 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2770 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2771 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2772 return LOLR_Error;
2773}
2774
John McCall7edb5fd2010-01-26 07:16:45 +00002775void ADLResult::insert(NamedDecl *New) {
2776 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2777
2778 // If we haven't yet seen a decl for this key, or the last decl
2779 // was exactly this one, we're done.
2780 if (Old == 0 || Old == New) {
2781 Old = New;
2782 return;
2783 }
2784
2785 // Otherwise, decide which is a more recent redeclaration.
2786 FunctionDecl *OldFD, *NewFD;
2787 if (isa<FunctionTemplateDecl>(New)) {
2788 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2789 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2790 } else {
2791 OldFD = cast<FunctionDecl>(Old);
2792 NewFD = cast<FunctionDecl>(New);
2793 }
2794
2795 FunctionDecl *Cursor = NewFD;
2796 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002797 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002798
2799 // If we got to the end without finding OldFD, OldFD is the newer
2800 // declaration; leave things as they are.
2801 if (!Cursor) return;
2802
2803 // If we do find OldFD, then NewFD is newer.
2804 if (Cursor == OldFD) break;
2805
2806 // Otherwise, keep looking.
2807 }
2808
2809 Old = New;
2810}
2811
Sebastian Redl644be852009-10-23 19:23:15 +00002812void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm834c0582013-08-09 18:02:13 +00002813 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002814 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002815 // Find all of the associated namespaces and classes based on the
2816 // arguments we have.
2817 AssociatedNamespaceSet AssociatedNamespaces;
2818 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002819 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002820 AssociatedNamespaces,
2821 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002822
Sebastian Redl644be852009-10-23 19:23:15 +00002823 QualType T1, T2;
2824 if (Operator) {
2825 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002826 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002827 T2 = Args[1]->getType();
2828 }
2829
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002830 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002831 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2832 // and let Y be the lookup set produced by argument dependent
2833 // lookup (defined as follows). If X contains [...] then Y is
2834 // empty. Otherwise Y is the set of declarations found in the
2835 // namespaces associated with the argument types as described
2836 // below. The set of declarations found by the lookup of the name
2837 // is the union of X and Y.
2838 //
2839 // Here, we compute Y and add its members to the overloaded
2840 // candidate set.
2841 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002842 NSEnd = AssociatedNamespaces.end();
2843 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002844 // When considering an associated namespace, the lookup is the
2845 // same as the lookup performed when the associated namespace is
2846 // used as a qualifier (3.4.3.2) except that:
2847 //
2848 // -- Any using-directives in the associated namespace are
2849 // ignored.
2850 //
John McCall6ff07852009-08-07 22:18:02 +00002851 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002852 // associated classes are visible within their respective
2853 // namespaces even if they are not visible during an ordinary
2854 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002855 DeclContext::lookup_result R = (*NS)->lookup(Name);
2856 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2857 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002858 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002859 // If the only declaration here is an ordinary friend, consider
2860 // it only if it was declared in an associated classes.
2861 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
Richard Smith22050f22013-07-17 23:53:16 +00002862 bool DeclaredInAssociatedClass = false;
2863 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2864 DeclContext *LexDC = DI->getLexicalDeclContext();
2865 if (isa<CXXRecordDecl>(LexDC) &&
2866 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2867 DeclaredInAssociatedClass = true;
2868 break;
2869 }
2870 }
2871 if (!DeclaredInAssociatedClass)
John McCall3f9a8a62009-08-11 06:59:38 +00002872 continue;
2873 }
Mike Stump1eb44332009-09-09 15:08:12 +00002874
John McCalla113e722010-01-26 06:04:06 +00002875 if (isa<UsingShadowDecl>(D))
2876 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002877
John McCalla113e722010-01-26 06:04:06 +00002878 if (isa<FunctionDecl>(D)) {
2879 if (Operator &&
2880 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2881 T1, T2, Context))
2882 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002883 } else if (!isa<FunctionTemplateDecl>(D))
2884 continue;
2885
2886 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002887 }
2888 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002889}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002890
2891//----------------------------------------------------------------------------
2892// Search for all visible declarations.
2893//----------------------------------------------------------------------------
2894VisibleDeclConsumer::~VisibleDeclConsumer() { }
2895
Richard Smithd67679d2013-08-20 20:35:18 +00002896bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2897
Douglas Gregor546be3c2009-12-30 17:04:44 +00002898namespace {
2899
2900class ShadowContextRAII;
2901
2902class VisibleDeclsRecord {
2903public:
2904 /// \brief An entry in the shadow map, which is optimized to store a
2905 /// single declaration (the common case) but can also store a list
2906 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002907 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002908
2909private:
2910 /// \brief A mapping from declaration names to the declarations that have
2911 /// this name within a particular scope.
2912 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2913
2914 /// \brief A list of shadow maps, which is used to model name hiding.
2915 std::list<ShadowMap> ShadowMaps;
2916
2917 /// \brief The declaration contexts we have already visited.
2918 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2919
2920 friend class ShadowContextRAII;
2921
2922public:
2923 /// \brief Determine whether we have already visited this context
2924 /// (and, if not, note that we are going to visit that context now).
2925 bool visitedContext(DeclContext *Ctx) {
2926 return !VisitedContexts.insert(Ctx);
2927 }
2928
Douglas Gregor8071e422010-08-15 06:18:01 +00002929 bool alreadyVisitedContext(DeclContext *Ctx) {
2930 return VisitedContexts.count(Ctx);
2931 }
2932
Douglas Gregor546be3c2009-12-30 17:04:44 +00002933 /// \brief Determine whether the given declaration is hidden in the
2934 /// current scope.
2935 ///
2936 /// \returns the declaration that hides the given declaration, or
2937 /// NULL if no such declaration exists.
2938 NamedDecl *checkHidden(NamedDecl *ND);
2939
2940 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002941 void add(NamedDecl *ND) {
2942 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2943 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002944};
2945
2946/// \brief RAII object that records when we've entered a shadow context.
2947class ShadowContextRAII {
2948 VisibleDeclsRecord &Visible;
2949
2950 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2951
2952public:
2953 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2954 Visible.ShadowMaps.push_back(ShadowMap());
2955 }
2956
2957 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002958 Visible.ShadowMaps.pop_back();
2959 }
2960};
2961
2962} // end anonymous namespace
2963
Douglas Gregor546be3c2009-12-30 17:04:44 +00002964NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002965 // Look through using declarations.
2966 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002967
Douglas Gregor546be3c2009-12-30 17:04:44 +00002968 unsigned IDNS = ND->getIdentifierNamespace();
2969 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2970 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2971 SM != SMEnd; ++SM) {
2972 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2973 if (Pos == SM->end())
2974 continue;
2975
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002976 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002977 IEnd = Pos->second.end();
2978 I != IEnd; ++I) {
2979 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002980 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002981 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002982 Decl::IDNS_ObjCProtocol)))
2983 continue;
2984
2985 // Protocols are in distinct namespaces from everything else.
2986 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2987 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2988 (*I)->getIdentifierNamespace() != IDNS)
2989 continue;
2990
Douglas Gregor0cc84042010-01-14 15:47:35 +00002991 // Functions and function templates in the same scope overload
2992 // rather than hide. FIXME: Look for hiding based on function
2993 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002994 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002995 ND->isFunctionOrFunctionTemplate() &&
2996 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002997 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002998
Douglas Gregor546be3c2009-12-30 17:04:44 +00002999 // We've found a declaration that hides this one.
3000 return *I;
3001 }
3002 }
3003
3004 return 0;
3005}
3006
3007static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3008 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003009 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00003010 VisibleDeclConsumer &Consumer,
3011 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00003012 if (!Ctx)
3013 return;
3014
Douglas Gregor546be3c2009-12-30 17:04:44 +00003015 // Make sure we don't visit the same context twice.
3016 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3017 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003018
Douglas Gregor4923aa22010-07-02 20:37:36 +00003019 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3020 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3021
Douglas Gregor546be3c2009-12-30 17:04:44 +00003022 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00003023 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
3024 LEnd = Ctx->lookups_end();
3025 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003026 DeclContext::lookup_result R = *L;
3027 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3028 ++I) {
3029 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00003030 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003031 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003032 Visited.add(ND);
3033 }
Douglas Gregor70c23352010-12-09 21:44:02 +00003034 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003035 }
3036 }
3037
3038 // Traverse using directives for qualified name lookup.
3039 if (QualifiedNameLookup) {
3040 ShadowContextRAII Shadow(Visited);
3041 DeclContext::udir_iterator I, E;
3042 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003043 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003044 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003045 }
3046 }
3047
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003048 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003049 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00003050 if (!Record->hasDefinition())
3051 return;
3052
Douglas Gregor546be3c2009-12-30 17:04:44 +00003053 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
3054 BEnd = Record->bases_end();
3055 B != BEnd; ++B) {
3056 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003057
Douglas Gregor546be3c2009-12-30 17:04:44 +00003058 // Don't look into dependent bases, because name lookup can't look
3059 // there anyway.
3060 if (BaseType->isDependentType())
3061 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003062
Douglas Gregor546be3c2009-12-30 17:04:44 +00003063 const RecordType *Record = BaseType->getAs<RecordType>();
3064 if (!Record)
3065 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003066
Douglas Gregor546be3c2009-12-30 17:04:44 +00003067 // FIXME: It would be nice to be able to determine whether referencing
3068 // a particular member would be ambiguous. For example, given
3069 //
3070 // struct A { int member; };
3071 // struct B { int member; };
3072 // struct C : A, B { };
3073 //
3074 // void f(C *c) { c->### }
3075 //
3076 // accessing 'member' would result in an ambiguity. However, we
3077 // could be smart enough to qualify the member with the base
3078 // class, e.g.,
3079 //
3080 // c->B::member
3081 //
3082 // or
3083 //
3084 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003085
Douglas Gregor546be3c2009-12-30 17:04:44 +00003086 // Find results in this base class (and its bases).
3087 ShadowContextRAII Shadow(Visited);
3088 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003089 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003090 }
3091 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003092
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003093 // Traverse the contexts of Objective-C classes.
3094 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3095 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00003096 for (ObjCInterfaceDecl::visible_categories_iterator
3097 Cat = IFace->visible_categories_begin(),
3098 CatEnd = IFace->visible_categories_end();
3099 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003100 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00003101 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003102 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003103 }
3104
3105 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003106 for (ObjCInterfaceDecl::all_protocol_iterator
3107 I = IFace->all_referenced_protocol_begin(),
3108 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003109 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003110 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003111 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003112 }
3113
3114 // Traverse the superclass.
3115 if (IFace->getSuperClass()) {
3116 ShadowContextRAII Shadow(Visited);
3117 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003118 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003120
Douglas Gregorc220a182010-04-19 18:02:19 +00003121 // If there is an implementation, traverse it. We do this to find
3122 // synthesized ivars.
3123 if (IFace->getImplementation()) {
3124 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003125 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00003126 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00003127 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003128 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3129 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3130 E = Protocol->protocol_end(); I != E; ++I) {
3131 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003132 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003133 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003134 }
3135 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3136 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3137 E = Category->protocol_end(); I != E; ++I) {
3138 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003139 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003140 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003141 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003142
Douglas Gregorc220a182010-04-19 18:02:19 +00003143 // If there is an implementation, traverse it.
3144 if (Category->getImplementation()) {
3145 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003146 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00003147 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003148 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003149 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003150}
3151
3152static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3153 UnqualUsingDirectiveSet &UDirs,
3154 VisibleDeclConsumer &Consumer,
3155 VisibleDeclsRecord &Visited) {
3156 if (!S)
3157 return;
3158
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159 if (!S->getEntity() ||
3160 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00003161 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00003162 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3163 // Walk through the declarations in this Scope.
3164 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3165 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003166 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003167 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003168 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003169 Visited.add(ND);
3170 }
3171 }
3172 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003173
Douglas Gregor711be1e2010-03-15 14:33:29 +00003174 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003175 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003176 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003177 // Look into this scope's declaration context, along with any of its
3178 // parent lookup contexts (e.g., enclosing classes), up to the point
3179 // where we hit the context stored in the next outer scope.
3180 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003181 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003182
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003183 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003184 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003185 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3186 if (Method->isInstanceMethod()) {
3187 // For instance methods, look for ivars in the method's interface.
3188 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3189 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003190 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003191 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithd67679d2013-08-20 20:35:18 +00003192 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003193 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003194 }
3195
3196 // We've already performed all of the name lookup that we need
3197 // to for Objective-C methods; the next context will be the
3198 // outer scope.
3199 break;
3200 }
3201
Douglas Gregor546be3c2009-12-30 17:04:44 +00003202 if (Ctx->isFunctionOrMethod())
3203 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003204
3205 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003206 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003207 }
3208 } else if (!S->getParent()) {
3209 // Look into the translation unit scope. We walk through the translation
3210 // unit's declaration context, because the Scope itself won't have all of
3211 // the declarations if we loaded a precompiled header.
3212 // FIXME: We would like the translation unit's Scope object to point to the
3213 // translation unit, so we don't need this special "if" branch. However,
3214 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003216 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003217 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003218 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003219 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003220 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003221 }
3222
Douglas Gregor546be3c2009-12-30 17:04:44 +00003223 if (Entity) {
3224 // Lookup visible declarations in any namespaces found by using
3225 // directives.
3226 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3227 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3228 for (; UI != UEnd; ++UI)
3229 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003230 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003231 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003232 }
3233
3234 // Lookup names in the parent scope.
3235 ShadowContextRAII Shadow(Visited);
3236 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3237}
3238
3239void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003240 VisibleDeclConsumer &Consumer,
3241 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003242 // Determine the set of using directives available during
3243 // unqualified name lookup.
3244 Scope *Initial = S;
3245 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003246 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003247 // Find the first namespace or translation-unit scope.
3248 while (S && !isNamespaceOrTranslationUnitScope(S))
3249 S = S->getParent();
3250
3251 UDirs.visitScopeChain(Initial, S);
3252 }
3253 UDirs.done();
3254
3255 // Look for visible declarations.
3256 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003257 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003258 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003259 if (!IncludeGlobalScope)
3260 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003261 ShadowContextRAII Shadow(Visited);
3262 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3263}
3264
3265void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003266 VisibleDeclConsumer &Consumer,
3267 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003268 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003269 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003270 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003271 if (!IncludeGlobalScope)
3272 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003273 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003274 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003275 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003276}
3277
Chris Lattner4ae493c2011-02-18 02:08:43 +00003278/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003279/// If GnuLabelLoc is a valid source location, then this is a definition
3280/// of an __label__ label name, otherwise it is a normal label definition
3281/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003282LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003283 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003284 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003285 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003286
3287 if (GnuLabelLoc.isValid()) {
3288 // Local label definitions always shadow existing labels.
3289 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3290 Scope *S = CurScope;
3291 PushOnScopeChains(Res, S, true);
3292 return cast<LabelDecl>(Res);
3293 }
3294
3295 // Not a GNU local label.
3296 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3297 // If we found a label, check to see if it is in the same context as us.
3298 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003299 if (Res && Res->getDeclContext() != CurContext)
3300 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003301 if (Res == 0) {
3302 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003303 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3304 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003305 assert(S && "Not in a function?");
3306 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003307 }
Chris Lattner337e5502011-02-18 01:27:55 +00003308 return cast<LabelDecl>(Res);
3309}
3310
3311//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003312// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003313//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003314
3315namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003316
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003317typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003318typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003319typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003320
3321static const unsigned MaxTypoDistanceResultSets = 5;
3322
Douglas Gregor546be3c2009-12-30 17:04:44 +00003323class TypoCorrectionConsumer : public VisibleDeclConsumer {
3324 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003325 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003326
3327 /// \brief The results found that have the smallest edit distance
3328 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003329 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003330 /// The pointer value being set to the current DeclContext indicates
3331 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003332 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003333
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003334 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003335
Douglas Gregor546be3c2009-12-30 17:04:44 +00003336public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003337 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003338 : Typo(Typo->getName()),
Richard Smithd67679d2013-08-20 20:35:18 +00003339 SemaRef(SemaRef) {}
3340
3341 bool includeHiddenDecls() const { return true; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003342
Erik Verbruggend1205962011-10-06 07:27:49 +00003343 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3344 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003345 void FoundName(StringRef Name);
3346 void addKeywordResult(StringRef Keyword);
3347 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003348 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003349 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003350
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003351 typedef TypoResultsMap::iterator result_iterator;
3352 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003353 distance_iterator begin() { return CorrectionResults.begin(); }
3354 distance_iterator end() { return CorrectionResults.end(); }
3355 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3356 unsigned size() const { return CorrectionResults.size(); }
3357 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003358
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003359 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003360 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003361 }
3362
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003363 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003364 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003365 return (std::numeric_limits<unsigned>::max)();
3366
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003367 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003368 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003369 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003370
3371 TypoResultsMap &getBestResults() {
3372 return CorrectionResults.begin()->second;
3373 }
3374
Douglas Gregor546be3c2009-12-30 17:04:44 +00003375};
3376
3377}
3378
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003380 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003381 // Don't consider hidden names for typo correction.
3382 if (Hiding)
3383 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003384
Douglas Gregor546be3c2009-12-30 17:04:44 +00003385 // Only consider entities with identifiers for names, ignoring
3386 // special names (constructors, overloaded operators, selectors,
3387 // etc.).
3388 IdentifierInfo *Name = ND->getIdentifier();
3389 if (!Name)
3390 return;
3391
Richard Smithd67679d2013-08-20 20:35:18 +00003392 // Only consider visible declarations and declarations from modules with
3393 // names that exactly match.
3394 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3395 !findAcceptableDecl(SemaRef, ND))
3396 return;
3397
Douglas Gregor95f42922010-10-14 22:11:03 +00003398 FoundName(Name->getName());
3399}
3400
Chris Lattner5f9e2722011-07-23 10:55:15 +00003401void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003402 // Use a simple length-based heuristic to determine the minimum possible
3403 // edit distance. If the minimum isn't good enough, bail out early.
3404 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003405 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003406 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003407
Douglas Gregora1194772010-10-19 22:14:33 +00003408 // Compute an upper bound on the allowable edit distance, so that the
3409 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003410 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003411
Douglas Gregor546be3c2009-12-30 17:04:44 +00003412 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003413 // entity, and add the identifier to the list of results.
3414 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003415}
3416
Chris Lattner5f9e2722011-07-23 10:55:15 +00003417void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003418 // Compute the edit distance between the typo and this keyword,
3419 // and add the keyword to the list of results.
3420 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003421}
3422
Chris Lattner5f9e2722011-07-23 10:55:15 +00003423void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003424 NamedDecl *ND,
3425 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003426 NestedNameSpecifier *NNS,
3427 bool isKeyword) {
3428 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3429 if (isKeyword) TC.makeKeyword();
3430 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003431}
3432
3433void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003434 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003435 TypoResultList &CList =
3436 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003437
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003438 if (!CList.empty() && !CList.back().isResolved())
3439 CList.pop_back();
3440 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3441 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3442 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3443 RI != RIEnd; ++RI) {
3444 // If the Correction refers to a decl already in the result list,
3445 // replace the existing result if the string representation of Correction
3446 // comes before the current result alphabetically, then stop as there is
3447 // nothing more to be done to add Correction to the candidate set.
3448 if (RI->getCorrectionDecl() == NewND) {
3449 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3450 *RI = Correction;
3451 return;
3452 }
3453 }
3454 }
3455 if (CList.empty() || Correction.isResolved())
3456 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003457
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003458 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3459 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003460}
3461
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003462// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3463// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3464// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3465static void getNestedNameSpecifierIdentifiers(
3466 NestedNameSpecifier *NNS,
3467 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3468 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3469 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3470 else
3471 Identifiers.clear();
3472
3473 const IdentifierInfo *II = NULL;
3474
3475 switch (NNS->getKind()) {
3476 case NestedNameSpecifier::Identifier:
3477 II = NNS->getAsIdentifier();
3478 break;
3479
3480 case NestedNameSpecifier::Namespace:
3481 if (NNS->getAsNamespace()->isAnonymousNamespace())
3482 return;
3483 II = NNS->getAsNamespace()->getIdentifier();
3484 break;
3485
3486 case NestedNameSpecifier::NamespaceAlias:
3487 II = NNS->getAsNamespaceAlias()->getIdentifier();
3488 break;
3489
3490 case NestedNameSpecifier::TypeSpecWithTemplate:
3491 case NestedNameSpecifier::TypeSpec:
3492 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3493 break;
3494
3495 case NestedNameSpecifier::Global:
3496 return;
3497 }
3498
3499 if (II)
3500 Identifiers.push_back(II);
3501}
3502
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003503namespace {
3504
3505class SpecifierInfo {
3506 public:
3507 DeclContext* DeclCtx;
3508 NestedNameSpecifier* NameSpecifier;
3509 unsigned EditDistance;
3510
3511 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3512 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3513};
3514
Chris Lattner5f9e2722011-07-23 10:55:15 +00003515typedef SmallVector<DeclContext*, 4> DeclContextList;
3516typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003517
3518class NamespaceSpecifierSet {
3519 ASTContext &Context;
3520 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003521 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3522 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003523 bool isSorted;
3524
3525 SpecifierInfoList Specifiers;
3526 llvm::SmallSetVector<unsigned, 4> Distances;
3527 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3528
3529 /// \brief Helper for building the list of DeclContexts between the current
3530 /// context and the top of the translation unit
3531 static DeclContextList BuildContextChain(DeclContext *Start);
3532
3533 void SortNamespaces();
3534
3535 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003536 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3537 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003538 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003539 isSorted(false) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003540 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3541 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3542 CurNameSpecifierIdentifiers);
3543 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003544 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003545 // context.
3546 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3547 CEnd = CurContextChain.rend();
3548 C != CEnd; ++C) {
3549 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3550 CurContextIdentifiers.push_back(ND->getIdentifier());
3551 }
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003552
3553 // Add the global context as a NestedNameSpecifier
3554 Distances.insert(1);
3555 DistanceMap[1].push_back(
3556 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3557 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003558 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003559
3560 /// \brief Add the namespace to the set, computing the corresponding
3561 /// NestedNameSpecifier and its distance in the process.
3562 void AddNamespace(NamespaceDecl *ND);
3563
3564 typedef SpecifierInfoList::iterator iterator;
3565 iterator begin() {
3566 if (!isSorted) SortNamespaces();
3567 return Specifiers.begin();
3568 }
3569 iterator end() { return Specifiers.end(); }
3570};
3571
3572}
3573
3574DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0db9d202013-04-08 21:55:21 +00003575 assert(Start && "Building a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003576 DeclContextList Chain;
3577 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3578 DC = DC->getLookupParent()) {
3579 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3580 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3581 !(ND && ND->isAnonymousNamespace()))
3582 Chain.push_back(DC->getPrimaryContext());
3583 }
3584 return Chain;
3585}
3586
3587void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003588 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003589 sortedDistances.append(Distances.begin(), Distances.end());
3590
3591 if (sortedDistances.size() > 1)
3592 std::sort(sortedDistances.begin(), sortedDistances.end());
3593
3594 Specifiers.clear();
Craig Topper09d19ef2013-07-04 03:08:24 +00003595 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3596 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003597 DI != DIEnd; ++DI) {
3598 SpecifierInfoList &SpecList = DistanceMap[*DI];
3599 Specifiers.append(SpecList.begin(), SpecList.end());
3600 }
3601
3602 isSorted = true;
3603}
3604
3605void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003606 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003607 NestedNameSpecifier *NNS = NULL;
3608 unsigned NumSpecifiers = 0;
3609 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003610 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003611
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003612 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003613 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3614 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003615 C != CEnd && !NamespaceDeclChain.empty() &&
3616 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003617 NamespaceDeclChain.pop_back();
3618 }
3619
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003620 // Add an explicit leading '::' specifier if needed.
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00003621 if (NamespaceDeclChain.empty()) {
3622 NamespaceDeclChain = FullNamespaceDeclChain;
3623 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3624 } else if (NamespaceDecl *ND =
3625 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003626 IdentifierInfo *Name = ND->getIdentifier();
3627 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3628 Name) != CurContextIdentifiers.end() ||
3629 std::find(CurNameSpecifierIdentifiers.begin(),
3630 CurNameSpecifierIdentifiers.end(),
3631 Name) != CurNameSpecifierIdentifiers.end()) {
3632 NamespaceDeclChain = FullNamespaceDeclChain;
3633 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3634 }
3635 }
3636
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003637 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3638 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3639 CEnd = NamespaceDeclChain.rend();
3640 C != CEnd; ++C) {
3641 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3642 if (ND) {
3643 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3644 ++NumSpecifiers;
3645 }
3646 }
3647
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003648 // If the built NestedNameSpecifier would be replacing an existing
3649 // NestedNameSpecifier, use the number of component identifiers that
3650 // would need to be changed as the edit distance instead of the number
3651 // of components in the built NestedNameSpecifier.
3652 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3653 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3654 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3655 NumSpecifiers = llvm::ComputeEditDistance(
Robert Wilhelm834c0582013-08-09 18:02:13 +00003656 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3657 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003658 }
3659
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003660 isSorted = false;
3661 Distances.insert(NumSpecifiers);
3662 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003663}
3664
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003665/// \brief Perform name lookup for a possible result for typo correction.
3666static void LookupPotentialTypoResult(Sema &SemaRef,
3667 LookupResult &Res,
3668 IdentifierInfo *Name,
3669 Scope *S, CXXScopeSpec *SS,
3670 DeclContext *MemberContext,
3671 bool EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00003672 bool isObjCIvarLookup,
3673 bool FindHidden) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003674 Res.suppressDiagnostics();
3675 Res.clear();
3676 Res.setLookupName(Name);
Richard Smithd67679d2013-08-20 20:35:18 +00003677 Res.setAllowHidden(FindHidden);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003678 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003679 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003680 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003681 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3682 Res.addDecl(Ivar);
3683 Res.resolveKind();
3684 return;
3685 }
3686 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003687
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003688 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3689 Res.addDecl(Prop);
3690 Res.resolveKind();
3691 return;
3692 }
3693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003694
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003695 SemaRef.LookupQualifiedName(Res, MemberContext);
3696 return;
3697 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003698
3699 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003700 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003701
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003702 // Fake ivar lookup; this should really be part of
3703 // LookupParsedName.
3704 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3705 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003706 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003707 (Res.isSingleResult() &&
3708 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003710 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3711 Res.addDecl(IV);
3712 Res.resolveKind();
3713 }
3714 }
3715 }
3716}
3717
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003718/// \brief Add keywords to the consumer as possible typo corrections.
3719static void AddKeywordsToConsumer(Sema &SemaRef,
3720 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003721 Scope *S, CorrectionCandidateCallback &CCC,
3722 bool AfterNestedNameSpecifier) {
3723 if (AfterNestedNameSpecifier) {
3724 // For 'X::', we know exactly which keywords can appear next.
3725 Consumer.addKeywordResult("template");
3726 if (CCC.WantExpressionKeywords)
3727 Consumer.addKeywordResult("operator");
3728 return;
3729 }
3730
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003731 if (CCC.WantObjCSuper)
3732 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003733
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003734 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003735 // Add type-specifier keywords to the set of results.
Craig Topper3aa29df2013-07-15 08:24:27 +00003736 static const char *const CTypeSpecs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003737 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003738 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003739 "_Complex", "_Imaginary",
3740 // storage-specifiers as well
3741 "extern", "inline", "static", "typedef"
3742 };
3743
Craig Topperb9602322013-07-15 03:38:40 +00003744 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003745 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3746 Consumer.addKeywordResult(CTypeSpecs[I]);
3747
David Blaikie4e4d0842012-03-11 07:00:24 +00003748 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003749 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003750 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003751 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003752 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003753 Consumer.addKeywordResult("_Bool");
3754
David Blaikie4e4d0842012-03-11 07:00:24 +00003755 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003756 Consumer.addKeywordResult("class");
3757 Consumer.addKeywordResult("typename");
3758 Consumer.addKeywordResult("wchar_t");
3759
Richard Smith80ad52f2013-01-02 11:42:31 +00003760 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003761 Consumer.addKeywordResult("char16_t");
3762 Consumer.addKeywordResult("char32_t");
3763 Consumer.addKeywordResult("constexpr");
3764 Consumer.addKeywordResult("decltype");
3765 Consumer.addKeywordResult("thread_local");
3766 }
3767 }
3768
David Blaikie4e4d0842012-03-11 07:00:24 +00003769 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003770 Consumer.addKeywordResult("typeof");
3771 }
3772
David Blaikie4e4d0842012-03-11 07:00:24 +00003773 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003774 Consumer.addKeywordResult("const_cast");
3775 Consumer.addKeywordResult("dynamic_cast");
3776 Consumer.addKeywordResult("reinterpret_cast");
3777 Consumer.addKeywordResult("static_cast");
3778 }
3779
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003780 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003781 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003782 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003783 Consumer.addKeywordResult("false");
3784 Consumer.addKeywordResult("true");
3785 }
3786
David Blaikie4e4d0842012-03-11 07:00:24 +00003787 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topper3aa29df2013-07-15 08:24:27 +00003788 static const char *const CXXExprs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003789 "delete", "new", "operator", "throw", "typeid"
3790 };
Craig Topperb9602322013-07-15 03:38:40 +00003791 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003792 for (unsigned I = 0; I != NumCXXExprs; ++I)
3793 Consumer.addKeywordResult(CXXExprs[I]);
3794
3795 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3796 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3797 Consumer.addKeywordResult("this");
3798
Richard Smith80ad52f2013-01-02 11:42:31 +00003799 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003800 Consumer.addKeywordResult("alignof");
3801 Consumer.addKeywordResult("nullptr");
3802 }
3803 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003804
3805 if (SemaRef.getLangOpts().C11) {
3806 // FIXME: We should not suggest _Alignof if the alignof macro
3807 // is present.
3808 Consumer.addKeywordResult("_Alignof");
3809 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003810 }
3811
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003812 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003813 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3814 // Statements.
Craig Topper3aa29df2013-07-15 08:24:27 +00003815 static const char *const CStmts[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003816 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Topperb9602322013-07-15 03:38:40 +00003817 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003818 for (unsigned I = 0; I != NumCStmts; ++I)
3819 Consumer.addKeywordResult(CStmts[I]);
3820
David Blaikie4e4d0842012-03-11 07:00:24 +00003821 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003822 Consumer.addKeywordResult("catch");
3823 Consumer.addKeywordResult("try");
3824 }
3825
3826 if (S && S->getBreakParent())
3827 Consumer.addKeywordResult("break");
3828
3829 if (S && S->getContinueParent())
3830 Consumer.addKeywordResult("continue");
3831
3832 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3833 Consumer.addKeywordResult("case");
3834 Consumer.addKeywordResult("default");
3835 }
3836 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003837 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003838 Consumer.addKeywordResult("namespace");
3839 Consumer.addKeywordResult("template");
3840 }
3841
3842 if (S && S->isClassScope()) {
3843 Consumer.addKeywordResult("explicit");
3844 Consumer.addKeywordResult("friend");
3845 Consumer.addKeywordResult("mutable");
3846 Consumer.addKeywordResult("private");
3847 Consumer.addKeywordResult("protected");
3848 Consumer.addKeywordResult("public");
3849 Consumer.addKeywordResult("virtual");
3850 }
3851 }
3852
David Blaikie4e4d0842012-03-11 07:00:24 +00003853 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003854 Consumer.addKeywordResult("using");
3855
Richard Smith80ad52f2013-01-02 11:42:31 +00003856 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003857 Consumer.addKeywordResult("static_assert");
3858 }
3859 }
3860}
3861
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003862static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3863 TypoCorrection &Candidate) {
3864 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3865 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3866}
3867
Richard Smithd67679d2013-08-20 20:35:18 +00003868/// \brief Check whether the declarations found for a typo correction are
3869/// visible, and if none of them are, convert the correction to an 'import
3870/// a module' correction.
3871static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3872 DeclarationName TypoName) {
3873 if (TC.begin() == TC.end())
3874 return;
3875
3876 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3877
3878 for (/**/; DI != DE; ++DI)
3879 if (!LookupResult::isVisible(SemaRef, *DI))
3880 break;
3881 // Nothing to do if all decls are visible.
3882 if (DI == DE)
3883 return;
3884
3885 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3886 bool AnyVisibleDecls = !NewDecls.empty();
3887
3888 for (/**/; DI != DE; ++DI) {
3889 NamedDecl *VisibleDecl = *DI;
3890 if (!LookupResult::isVisible(SemaRef, *DI))
3891 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3892
3893 if (VisibleDecl) {
3894 if (!AnyVisibleDecls) {
3895 // Found a visible decl, discard all hidden ones.
3896 AnyVisibleDecls = true;
3897 NewDecls.clear();
3898 }
3899 NewDecls.push_back(VisibleDecl);
3900 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3901 NewDecls.push_back(*DI);
3902 }
3903
3904 if (NewDecls.empty())
3905 TC = TypoCorrection();
3906 else {
3907 TC.setCorrectionDecls(NewDecls);
3908 TC.setRequiresImport(!AnyVisibleDecls);
3909 }
3910}
3911
Douglas Gregor546be3c2009-12-30 17:04:44 +00003912/// \brief Try to "correct" a typo in the source code by finding
3913/// visible declarations whose names are similar to the name that was
3914/// present in the source code.
3915///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003916/// \param TypoName the \c DeclarationNameInfo structure that contains
3917/// the name that was present in the source code along with its location.
3918///
3919/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003920///
3921/// \param S the scope in which name lookup occurs.
3922///
3923/// \param SS the nested-name-specifier that precedes the name we're
3924/// looking for, if present.
3925///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003926/// \param CCC A CorrectionCandidateCallback object that provides further
3927/// validation of typo correction candidates. It also provides flags for
3928/// determining the set of keywords permitted.
3929///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003930/// \param MemberContext if non-NULL, the context in which to look for
3931/// a member access expression.
3932///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003933/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003934/// the nested-name-specifier SS.
3935///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003936/// \param OPT when non-NULL, the search for visible declarations will
3937/// also walk the protocols in the qualified interfaces of \p OPT.
3938///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003939/// \returns a \c TypoCorrection containing the corrected name if the typo
3940/// along with information such as the \c NamedDecl where the corrected name
3941/// was declared, and any additional \c NestedNameSpecifier needed to access
3942/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3943TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3944 Sema::LookupNameKind LookupKind,
3945 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003946 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003947 DeclContext *MemberContext,
3948 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003949 const ObjCObjectPointerType *OPT) {
Kaelyn Uhrain70571f42013-08-12 19:54:38 +00003950 // Always let the ExternalSource have the first chance at correction, even
3951 // if we would otherwise have given up.
3952 if (ExternalSource) {
3953 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
3954 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
3955 return Correction;
3956 }
3957
David Blaikie4e4d0842012-03-11 07:00:24 +00003958 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003959 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003960
Francois Pichet4d604d62011-12-03 15:55:29 +00003961 // In Microsoft mode, don't perform typo correction in a template member
3962 // function dependent context because it interferes with the "lookup into
3963 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003964 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003965 isa<CXXMethodDecl>(CurContext))
3966 return TypoCorrection();
3967
Douglas Gregor546be3c2009-12-30 17:04:44 +00003968 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003969 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003970 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003971 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003972
3973 // If the scope specifier itself was invalid, don't try to correct
3974 // typos.
3975 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003976 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003977
3978 // Never try to correct typos during template deduction or
3979 // instantiation.
3980 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003981 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003982
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003983 // Don't try to correct 'super'.
3984 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3985 return TypoCorrection();
3986
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003987 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003988
3989 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003990
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003991 // If a callback object considers an empty typo correction candidate to be
3992 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003993 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003994 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003995
Douglas Gregoraaf87162010-04-14 20:04:41 +00003996 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003997 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003998 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003999 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004000 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004001
4002 // Look in qualified interfaces.
4003 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004004 for (ObjCObjectPointerType::qual_iterator
4005 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004006 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004007 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004008 }
4009 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004010 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4011 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004012 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004013
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004014 // Provide a stop gap for files that are just seriously broken. Trying
4015 // to correct all typos can turn into a HUGE performance penalty, causing
4016 // some files to take minutes to get rejected by the parser.
4017 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004018 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004019 ++TyposCorrected;
4020
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004021 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00004022 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004023 IsUnqualifiedLookup = true;
4024 UnqualifiedTyposCorrectedMap::iterator Cached
4025 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004026 if (Cached != UnqualifiedTyposCorrected.end()) {
4027 // Add the cached value, unless it's a keyword or fails validation. In the
4028 // keyword case, we'll end up adding the keyword below.
4029 if (Cached->second) {
4030 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004031 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004032 Consumer.addCorrection(Cached->second);
4033 } else {
4034 // Only honor no-correction cache hits when a callback that will validate
4035 // correction candidates is not being used.
4036 if (!ValidatingCallback)
4037 return TypoCorrection();
4038 }
4039 }
4040 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004041 // Provide a stop gap for files that are just seriously broken. Trying
4042 // to correct all typos can turn into a HUGE performance penalty, causing
4043 // some files to take minutes to get rejected by the parser.
4044 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004045 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004046 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004047 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004048
Douglas Gregor01798682012-03-26 16:54:18 +00004049 // Determine whether we are going to search in the various namespaces for
4050 // corrections.
4051 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00004052 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00004053 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Richard Smithd67679d2013-08-20 20:35:18 +00004054 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004055 // adding or changing the nested name specifier.
4056 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00004057
4058 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004059 // For unqualified lookup, look through all of the names that we have
4060 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004061 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004062 for (IdentifierTable::iterator I = Context.Idents.begin(),
4063 IEnd = Context.Idents.end();
4064 I != IEnd; ++I)
4065 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004066
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004067 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004068 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004069 if (IdentifierInfoLookup *External
4070 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00004071 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004072 do {
4073 StringRef Name = Iter->Next();
4074 if (Name.empty())
4075 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00004076
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004077 Consumer.FoundName(Name);
4078 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00004079 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004080 }
4081
Richard Smith0f4b5be2012-06-08 21:35:42 +00004082 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004083
Douglas Gregoraaf87162010-04-14 20:04:41 +00004084 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004085 if (Consumer.empty()) {
4086 // If this was an unqualified lookup, note that no correction was found.
4087 if (IsUnqualifiedLookup)
4088 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004089
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004090 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004091 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004092
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004093 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4094 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004095 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004096 if (ED > 0 && Typo->getName().size() / ED < 3) {
4097 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00004098 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004099 (void)UnqualifiedTyposCorrected[Typo];
4100
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004101 return TypoCorrection();
4102 }
4103
Douglas Gregor01798682012-03-26 16:54:18 +00004104 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4105 // to search those namespaces.
4106 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004107 // Load any externally-known namespaces.
4108 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004109 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004110 LoadedExternalKnownNamespaces = true;
4111 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4112 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4113 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4114 }
4115
Nick Lewycky01a41142013-01-26 00:35:08 +00004116 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004117 KNI = KnownNamespaces.begin(),
4118 KNIEnd = KnownNamespaces.end();
4119 KNI != KNIEnd; ++KNI)
4120 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004121 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004122
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004123 // Weed out any names that could not be found by name lookup or, if a
4124 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004125 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004126 LookupResult TmpRes(*this, TypoName, LookupKind);
4127 TmpRes.suppressDiagnostics();
4128 while (!Consumer.empty()) {
4129 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
4130 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004131 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4132 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004133 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004134 // If we only want nested name specifier corrections, ignore potential
4135 // corrections that have a different base identifier from the typo.
4136 if (AllowOnlyNNSChanges &&
4137 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4138 TypoCorrectionConsumer::result_iterator Prev = I;
4139 ++I;
4140 DI->second.erase(Prev);
4141 continue;
4142 }
4143
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004144 // If the item already has been looked up or is a keyword, keep it.
4145 // If a validator callback object was given, drop the correction
4146 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004147 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00004148 for (TypoResultList::iterator RI = I->second.begin();
4149 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004150 TypoResultList::iterator Prev = RI;
4151 ++RI;
4152 if (Prev->isResolved()) {
4153 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00004154 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004155 else
4156 Viable = true;
4157 }
4158 }
4159 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004160 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004161 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004162 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004163 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004164 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00004165 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004166 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004167
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004168 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004169 TypoCorrection &Candidate = I->second.front();
4170 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004171 DeclContext *TempMemberContext = MemberContext;
4172 CXXScopeSpec *TempSS = SS;
4173retry_lookup:
4174 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4175 TempMemberContext, EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00004176 CCC.IsObjCIvarLookup,
4177 Name == TypoName.getName() &&
4178 !Candidate.WillReplaceSpecifier());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004179
4180 switch (TmpRes.getResultKind()) {
4181 case LookupResult::NotFound:
4182 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004183 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004184 if (TempSS) {
4185 // Immediately retry the lookup without the given CXXScopeSpec
4186 TempSS = NULL;
4187 Candidate.WillReplaceSpecifier(true);
4188 goto retry_lookup;
4189 }
4190 if (TempMemberContext) {
4191 if (SS && !TempSS)
4192 TempSS = SS;
4193 TempMemberContext = NULL;
4194 goto retry_lookup;
4195 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004196 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004197 // We didn't find this name in our scope, or didn't like what we found;
4198 // ignore it.
4199 {
4200 TypoCorrectionConsumer::result_iterator Next = I;
4201 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004202 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004203 I = Next;
4204 }
4205 break;
4206
4207 case LookupResult::Ambiguous:
4208 // We don't deal with ambiguities.
4209 return TypoCorrection();
4210
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004211 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004212 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004213 // Store all of the Decls for overloaded symbols
4214 for (LookupResult::iterator TRD = TmpRes.begin(),
4215 TRDEnd = TmpRes.end();
4216 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004217 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004218 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004219 if (!isCandidateViable(CCC, Candidate)) {
4220 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004221 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004222 }
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004223 break;
4224 }
4225
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004226 case LookupResult::Found: {
4227 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004228 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004229 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004230 if (!isCandidateViable(CCC, Candidate)) {
4231 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004232 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004233 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004234 break;
4235 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004236
4237 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004238 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004239
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004240 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004241 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00004242 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004243 // If there are results in the closest possible bucket, stop
4244 break;
4245
4246 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004247 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004248 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004249 for (SmallVector<TypoCorrection,
4250 16>::iterator QRI = QualifiedResults.begin(),
4251 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004252 QRI != QRIEnd; ++QRI) {
4253 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4254 NIEnd = Namespaces.end();
4255 NI != NIEnd; ++NI) {
4256 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004257
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004258 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004259 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004260 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004261
4262 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004263 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004264 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4265
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004266 // Any corrections added below will be validated in subsequent
4267 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004268 switch (TmpRes.getResultKind()) {
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004269 case LookupResult::Found:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004270 case LookupResult::FoundOverloaded: {
4271 TypoCorrection TC(*QRI);
4272 TC.setCorrectionSpecifier(NI->NameSpecifier);
4273 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004274 TC.setCallbackDistance(0); // Reset the callback distance
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004275 for (LookupResult::iterator TRD = TmpRes.begin(),
4276 TRDEnd = TmpRes.end();
4277 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004278 TC.addCorrectionDecl(*TRD);
4279 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004280 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004281 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004282 case LookupResult::NotFound:
4283 case LookupResult::NotFoundInCurrentInstantiation:
4284 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004285 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004286 break;
4287 }
4288 }
4289 }
4290 }
4291
4292 QualifiedResults.clear();
4293 }
4294
4295 // No corrections remain...
4296 if (Consumer.empty()) return TypoCorrection();
4297
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004298 TypoResultsMap &BestResults = Consumer.getBestResults();
4299 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004300
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004301 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004302 // If this was an unqualified lookup and we believe the callback
4303 // object wouldn't have filtered out possible corrections, note
4304 // that no correction was found.
4305 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004306 (void)UnqualifiedTyposCorrected[Typo];
4307
4308 return TypoCorrection();
4309 }
4310
Douglas Gregore24b5752010-10-14 20:34:08 +00004311 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004312 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004313 const TypoResultList &CorrectionList = BestResults.begin()->second;
4314 const TypoCorrection &Result = CorrectionList.front();
4315 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316
Douglas Gregor53e4b552010-10-26 17:18:00 +00004317 // Don't correct to a keyword that's the same as the typo; the keyword
4318 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004319 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4320
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004321 // Record the correction for unqualified lookup.
4322 if (IsUnqualifiedLookup)
4323 UnqualifiedTyposCorrected[Typo] = Result;
4324
David Blaikie6952c012012-10-12 20:00:44 +00004325 TypoCorrection TC = Result;
4326 TC.setCorrectionRange(SS, TypoName);
Richard Smithd67679d2013-08-20 20:35:18 +00004327 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie6952c012012-10-12 20:00:44 +00004328 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004329 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004330 else if (BestResults.size() > 1
4331 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4332 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4333 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4334 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004335 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004336 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004337 // Prefer 'super' when we're completing in a message-receiver
4338 // context.
4339
4340 // Don't correct to a keyword that's the same as the typo; the keyword
4341 // wasn't actually in scope.
4342 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004343
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004344 // Record the correction for unqualified lookup.
4345 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004346 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004347
David Blaikie6952c012012-10-12 20:00:44 +00004348 TypoCorrection TC = BestResults["super"].front();
4349 TC.setCorrectionRange(SS, TypoName);
4350 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004351 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004352
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004353 // If this was an unqualified lookup and we believe the callback object did
4354 // not filter out possible corrections, note that no correction was found.
4355 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004356 (void)UnqualifiedTyposCorrected[Typo];
4357
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004358 return TypoCorrection();
4359}
4360
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004361void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4362 if (!CDecl) return;
4363
4364 if (isKeyword())
4365 CorrectionDecls.clear();
4366
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004367 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004368
4369 if (!CorrectionName)
4370 CorrectionName = CDecl->getDeclName();
4371}
4372
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004373std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4374 if (CorrectionNameSpec) {
4375 std::string tmpBuffer;
4376 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4377 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikie17828ca2013-05-14 21:04:00 +00004378 PrefixOStream << CorrectionName;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004379 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004380 }
4381
4382 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004383}
Kaelyn Uhrain20a7cf42013-04-03 16:59:49 +00004384
4385bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4386 if (!candidate.isResolved())
4387 return true;
4388
4389 if (candidate.isKeyword())
4390 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4391 WantRemainingKeywords || WantObjCSuper;
4392
4393 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4394 CDeclEnd = candidate.end();
4395 CDecl != CDeclEnd; ++CDecl) {
4396 if (!isa<TypeDecl>(*CDecl))
4397 return true;
4398 }
4399
4400 return WantTypeSpecifiers;
4401}
Kaelyn Uhrain761695f2013-07-08 23:13:39 +00004402
4403FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4404 bool HasExplicitTemplateArgs)
4405 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
4406 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4407 WantRemainingKeywords = false;
4408}
4409
4410bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4411 if (!candidate.getCorrectionDecl())
4412 return candidate.isKeyword();
4413
4414 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4415 DIEnd = candidate.end();
4416 DI != DIEnd; ++DI) {
4417 FunctionDecl *FD = 0;
4418 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4419 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4420 FD = FTD->getTemplatedDecl();
4421 if (!HasExplicitTemplateArgs && !FD) {
4422 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4423 // If the Decl is neither a function nor a template function,
4424 // determine if it is a pointer or reference to a function. If so,
4425 // check against the number of arguments expected for the pointee.
4426 QualType ValType = cast<ValueDecl>(ND)->getType();
4427 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4428 ValType = ValType->getPointeeType();
4429 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4430 if (FPT->getNumArgs() == NumArgs)
4431 return true;
4432 }
4433 }
4434 if (FD && FD->getNumParams() >= NumArgs &&
4435 FD->getMinRequiredArguments() <= NumArgs)
4436 return true;
4437 }
4438 return false;
4439}
Richard Smith2d670972013-08-17 00:46:16 +00004440
4441void Sema::diagnoseTypo(const TypoCorrection &Correction,
4442 const PartialDiagnostic &TypoDiag,
4443 bool ErrorRecovery) {
4444 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4445 ErrorRecovery);
4446}
4447
Richard Smithd67679d2013-08-20 20:35:18 +00004448/// Find which declaration we should import to provide the definition of
4449/// the given declaration.
4450static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4451 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4452 return VD->getDefinition();
4453 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4454 return FD->isDefined(FD) ? FD : 0;
4455 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4456 return TD->getDefinition();
4457 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4458 return ID->getDefinition();
4459 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4460 return PD->getDefinition();
4461 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4462 return getDefinitionToImport(TD->getTemplatedDecl());
4463 return 0;
4464}
4465
Richard Smith2d670972013-08-17 00:46:16 +00004466/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4467/// itself to allow external validation of the result, etc.
4468///
4469/// \param Correction The result of performing typo correction.
4470/// \param TypoDiag The diagnostic to produce. This will have the corrected
4471/// string added to it (and usually also a fixit).
4472/// \param PrevNote A note to use when indicating the location of the entity to
4473/// which we are correcting. Will have the correction string added to it.
4474/// \param ErrorRecovery If \c true (the default), the caller is going to
4475/// recover from the typo as if the corrected string had been typed.
4476/// In this case, \c PDiag must be an error, and we will attach a fixit
4477/// to it.
4478void Sema::diagnoseTypo(const TypoCorrection &Correction,
4479 const PartialDiagnostic &TypoDiag,
4480 const PartialDiagnostic &PrevNote,
4481 bool ErrorRecovery) {
4482 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4483 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4484 FixItHint FixTypo = FixItHint::CreateReplacement(
4485 Correction.getCorrectionRange(), CorrectedStr);
4486
Richard Smithd67679d2013-08-20 20:35:18 +00004487 // Maybe we're just missing a module import.
4488 if (Correction.requiresImport()) {
4489 NamedDecl *Decl = Correction.getCorrectionDecl();
4490 assert(Decl && "import required but no declaration to import");
4491
4492 // Suggest importing a module providing the definition of this entity, if
4493 // possible.
4494 const NamedDecl *Def = getDefinitionToImport(Decl);
4495 if (!Def)
4496 Def = Decl;
4497 Module *Owner = Def->getOwningModule();
4498 assert(Owner && "definition of hidden declaration is not in a module");
4499
4500 Diag(Correction.getCorrectionRange().getBegin(),
4501 diag::err_module_private_declaration)
4502 << Def << Owner->getFullModuleName();
4503 Diag(Def->getLocation(), diag::note_previous_declaration);
4504
4505 // Recover by implicitly importing this module.
4506 if (!isSFINAEContext() && ErrorRecovery)
4507 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4508 Owner);
4509 return;
4510 }
4511
Richard Smith2d670972013-08-17 00:46:16 +00004512 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4513 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4514
4515 NamedDecl *ChosenDecl =
4516 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4517 if (PrevNote.getDiagID() && ChosenDecl)
4518 Diag(ChosenDecl->getLocation(), PrevNote)
4519 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4520}