blob: 727f49b5fa4ba1152a8e6f1f5ac3f8bb1e1ea9ff [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewycky173a37a2012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ExternalSemaSource.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/TemplateDeduction.h"
34#include "clang/Sema/TypoCorrection.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/ADT/SetVector.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000038#include "llvm/ADT/StringMap.h"
Chris Lattnerb5f65472011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6e247262009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Nick Lewycky893a6ea2012-04-03 20:26:45 +000042#include <algorithm>
43#include <iterator>
Douglas Gregore24b5752010-10-14 20:34:08 +000044#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000045#include <list>
Douglas Gregord8bba9c2011-06-28 16:20:02 +000046#include <map>
Nick Lewycky893a6ea2012-04-03 20:26:45 +000047#include <set>
48#include <utility>
49#include <vector>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000050
51using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000052using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054namespace {
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000058
John McCalld7be78a2009-11-10 07:01:13 +000059 public:
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000064
John McCalld7be78a2009-11-10 07:01:13 +000065 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
67 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000068
John McCalld7be78a2009-11-10 07:01:13 +000069 const DeclContext *getNominatedNamespace() const {
70 return Nominated;
71 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000072
John McCalld7be78a2009-11-10 07:01:13 +000073 // Sort by the pointer value of the common ancestor.
74 struct Comparator {
75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76 return L.getCommonAncestor() < R.getCommonAncestor();
77 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000078
John McCalld7be78a2009-11-10 07:01:13 +000079 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
81 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000082
John McCalld7be78a2009-11-10 07:01:13 +000083 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
85 }
86 };
87 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000088
John McCalld7be78a2009-11-10 07:01:13 +000089 /// A collection of using directives, as used by C++ unqualified
90 /// lookup.
91 class UnqualUsingDirectiveSet {
Chris Lattner5f9e2722011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000096
John McCalld7be78a2009-11-10 07:01:13 +000097 public:
98 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000099
John McCalld7be78a2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCalld7be78a2009-11-10 07:01:13 +0000102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
105 DeclContext *InnermostFileDC
106 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000108
John McCalld7be78a2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky65daef12012-03-13 04:12:34 +0000110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000113 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
Nick Lewycky65daef12012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
John McCalld7be78a2009-11-10 07:01:13 +0000117 Scope::udir_iterator I = S->using_directives_begin(),
118 End = S->using_directives_end();
John McCalld7be78a2009-11-10 07:01:13 +0000119 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000120 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000121 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000122 }
123 }
John McCalld7be78a2009-11-10 07:01:13 +0000124
125 // Visits a context and collect all of its using directives
126 // recursively. Treats all using directives as if they were
127 // declared in the context.
128 //
129 // A given context is only every visited once, so it is important
130 // that contexts be visited from the inside out in order to get
131 // the effective DCs right.
132 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
133 if (!visited.insert(DC))
134 return;
135
136 addUsingDirectives(DC, EffectiveDC);
137 }
138
139 // Visits a using directive and collects all of its using
140 // directives recursively. Treats all using directives as if they
141 // were declared in the effective DC.
142 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (!visited.insert(NS))
145 return;
146
147 addUsingDirective(UD, EffectiveDC);
148 addUsingDirectives(NS, EffectiveDC);
149 }
150
151 // Adds all the using directives in a context (and those nominated
152 // by its using directives, transitively) as if they appeared in
153 // the given effective context.
154 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000155 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-11-10 07:01:13 +0000156 while (true) {
157 DeclContext::udir_iterator I, End;
158 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
159 UsingDirectiveDecl *UD = *I;
160 DeclContext *NS = UD->getNominatedNamespace();
161 if (visited.insert(NS)) {
162 addUsingDirective(UD, EffectiveDC);
163 queue.push_back(NS);
164 }
165 }
166
167 if (queue.empty())
168 return;
169
170 DC = queue.back();
171 queue.pop_back();
172 }
173 }
174
175 // Add a using directive as if it had been declared in the given
176 // context. This helps implement C++ [namespace.udir]p3:
177 // The using-directive is transitive: if a scope contains a
178 // using-directive that nominates a second namespace that itself
179 // contains using-directives, the effect is as if the
180 // using-directives from the second namespace also appeared in
181 // the first.
182 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
183 // Find the common ancestor between the effective context and
184 // the nominated namespace.
185 DeclContext *Common = UD->getNominatedNamespace();
186 while (!Common->Encloses(EffectiveDC))
187 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000188 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000189
John McCalld7be78a2009-11-10 07:01:13 +0000190 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
191 }
192
193 void done() {
194 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
195 }
196
John McCalld7be78a2009-11-10 07:01:13 +0000197 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000198
John McCalld7be78a2009-11-10 07:01:13 +0000199 const_iterator begin() const { return list.begin(); }
200 const_iterator end() const { return list.end(); }
201
202 std::pair<const_iterator,const_iterator>
203 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000204 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000205 UnqualUsingEntry::Comparator());
206 }
207 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000208}
209
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210// Retrieve the set of identifier namespaces that correspond to a
211// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000212static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
213 bool CPlusPlus,
214 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000215 unsigned IDNS = 0;
216 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000217 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000218 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000219 case Sema::LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +0000220 case Sema::LookupLocalFriendName:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000221 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000222 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000223 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000224 if (Redeclaration)
225 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000226 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000227 break;
228
John McCall76d32642010-04-24 01:30:58 +0000229 case Sema::LookupOperatorName:
230 // Operator lookup is its own crazy thing; it is not the same
231 // as (e.g.) looking up an operator name for redeclaration.
232 assert(!Redeclaration && "cannot do redeclaration operator lookup");
233 IDNS = Decl::IDNS_NonMemberOperator;
234 break;
235
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000236 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000237 if (CPlusPlus) {
238 IDNS = Decl::IDNS_Type;
239
240 // When looking for a redeclaration of a tag name, we add:
241 // 1) TagFriend to find undeclared friend decls
242 // 2) Namespace because they can't "overload" with tag decls.
243 // 3) Tag because it includes class templates, which can't
244 // "overload" with tag decls.
245 if (Redeclaration)
246 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
247 } else {
248 IDNS = Decl::IDNS_Tag;
249 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000251 case Sema::LookupLabel:
252 IDNS = Decl::IDNS_Label;
253 break;
254
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000255 case Sema::LookupMemberName:
256 IDNS = Decl::IDNS_Member;
257 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000258 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000259 break;
260
261 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
263 break;
264
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000265 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000266 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000267 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000268
John McCall9f54ad42009-12-10 09:41:52 +0000269 case Sema::LookupUsingDeclName:
270 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
271 | Decl::IDNS_Member | Decl::IDNS_Using;
272 break;
273
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000274 case Sema::LookupObjCProtocolName:
275 IDNS = Decl::IDNS_ObjCProtocol;
276 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000277
Douglas Gregor8071e422010-08-15 06:18:01 +0000278 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000279 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000280 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
281 | Decl::IDNS_Type;
282 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000283 }
284 return IDNS;
285}
286
John McCall1d7c5282009-12-18 10:40:03 +0000287void LookupResult::configure() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000288 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000289 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000290
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000291 if (!isForRedeclaration()) {
Douglas Gregor96df3562013-04-03 23:06:26 +0000292 // If we're looking for one of the allocation or deallocation
293 // operators, make sure that the implicitly-declared new and delete
294 // operators can be found.
Abramo Bagnara25777432010-08-11 22:01:17 +0000295 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000296 case OO_New:
297 case OO_Delete:
298 case OO_Array_New:
299 case OO_Array_Delete:
300 SemaRef.DeclareGlobalNewDelete();
301 break;
302
303 default:
304 break;
305 }
Douglas Gregor96df3562013-04-03 23:06:26 +0000306
307 // Compiler builtins are always visible, regardless of where they end
308 // up being declared.
309 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
310 if (unsigned BuiltinID = Id->getBuiltinID()) {
311 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
312 AllowHidden = true;
313 }
314 }
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000315 }
John McCall1d7c5282009-12-18 10:40:03 +0000316}
317
Daniel Dunbarc2bd73b2012-03-08 01:43:06 +0000318void LookupResult::sanityImpl() const {
319 // Note that this function is never called by NDEBUG builds. See
320 // LookupResult::sanity().
John McCall2a7fb272010-08-25 05:32:35 +0000321 assert(ResultKind != NotFound || Decls.size() == 0);
322 assert(ResultKind != Found || Decls.size() == 1);
323 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
324 (Decls.size() == 1 &&
325 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
326 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
327 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000328 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
329 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000330 assert((Paths != NULL) == (ResultKind == Ambiguous &&
331 (Ambiguity == AmbiguousBaseSubobjectTypes ||
332 Ambiguity == AmbiguousBaseSubobjects)));
333}
John McCall2a7fb272010-08-25 05:32:35 +0000334
John McCallf36e02d2009-10-09 21:13:30 +0000335// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000336void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000337 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000338}
339
John McCall7453ed42009-11-22 00:44:51 +0000340/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000341void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000342 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000343
John McCallf36e02d2009-10-09 21:13:30 +0000344 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000345 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000346 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000347 return;
348 }
349
John McCall7453ed42009-11-22 00:44:51 +0000350 // If there's a single decl, we need to examine it to decide what
351 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000352 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000353 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
354 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000355 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000356 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000357 ResultKind = FoundUnresolvedValue;
358 return;
359 }
John McCallf36e02d2009-10-09 21:13:30 +0000360
John McCall6e247262009-10-10 05:48:19 +0000361 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000362 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000363
John McCallf36e02d2009-10-09 21:13:30 +0000364 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000365 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000366
John McCallf36e02d2009-10-09 21:13:30 +0000367 bool Ambiguous = false;
368 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000369 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000370
371 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000372
John McCallf36e02d2009-10-09 21:13:30 +0000373 unsigned I = 0;
374 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000375 NamedDecl *D = Decls[I]->getUnderlyingDecl();
376 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000377
Argyrios Kyrtzidis745af1c2013-02-22 06:58:37 +0000378 // Ignore an invalid declaration unless it's the only one left.
379 if (D->isInvalidDecl() && I < N-1) {
380 Decls[I] = Decls[--N];
381 continue;
382 }
383
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000384 // Redeclarations of types via typedef can occur both within a scope
385 // and, through using declarations and directives, across scopes. There is
386 // no ambiguity if they all refer to the same type, so unique based on the
387 // canonical type.
388 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
389 if (!TD->getDeclContext()->isRecord()) {
390 QualType T = SemaRef.Context.getTypeDeclType(TD);
391 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
392 // The type is not unique; pull something off the back and continue
393 // at this index.
394 Decls[I] = Decls[--N];
395 continue;
396 }
397 }
398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000399
John McCall314be4e2009-11-17 07:50:12 +0000400 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000401 // If it's not unique, pull something off the back (and
402 // continue at this index).
403 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000404 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000405 }
406
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000407 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000408
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000409 if (isa<UnresolvedUsingValueDecl>(D)) {
410 HasUnresolved = true;
411 } else if (isa<TagDecl>(D)) {
412 if (HasTag)
413 Ambiguous = true;
414 UniqueTagIndex = I;
415 HasTag = true;
416 } else if (isa<FunctionTemplateDecl>(D)) {
417 HasFunction = true;
418 HasFunctionTemplate = true;
419 } else if (isa<FunctionDecl>(D)) {
420 HasFunction = true;
421 } else {
422 if (HasNonFunction)
423 Ambiguous = true;
424 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000425 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000426 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000427 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000428
John McCallf36e02d2009-10-09 21:13:30 +0000429 // C++ [basic.scope.hiding]p2:
430 // A class name or enumeration name can be hidden by the name of
431 // an object, function, or enumerator declared in the same
432 // scope. If a class or enumeration name and an object, function,
433 // or enumerator are declared in the same scope (in any order)
434 // with the same name, the class or enumeration name is hidden
435 // wherever the object, function, or enumerator name is visible.
436 // But it's still an error if there are distinct tag types found,
437 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000438 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000439 (HasFunction || HasNonFunction || HasUnresolved)) {
440 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
441 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
442 Decls[UniqueTagIndex] = Decls[--N];
443 else
444 Ambiguous = true;
445 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000446
John McCallf36e02d2009-10-09 21:13:30 +0000447 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000448
John McCallfda8e122009-12-03 00:58:24 +0000449 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000450 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000451
John McCallf36e02d2009-10-09 21:13:30 +0000452 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000453 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000454 else if (HasUnresolved)
455 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000456 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000457 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000458 else
John McCalla24dc2e2009-11-17 02:14:36 +0000459 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000460}
461
John McCall7d384dd2009-11-18 07:57:50 +0000462void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000463 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000464 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikie3bc93e32012-12-19 00:45:41 +0000465 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
466 DE = I->Decls.end(); DI != DE; ++DI)
John McCallf36e02d2009-10-09 21:13:30 +0000467 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000468}
469
John McCall7d384dd2009-11-18 07:57:50 +0000470void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000471 Paths = new CXXBasePaths;
472 Paths->swap(P);
473 addDeclsFromBasePaths(*Paths);
474 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000475 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000476}
477
John McCall7d384dd2009-11-18 07:57:50 +0000478void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000479 Paths = new CXXBasePaths;
480 Paths->swap(P);
481 addDeclsFromBasePaths(*Paths);
482 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000483 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000484}
485
Chris Lattner5f9e2722011-07-23 10:55:15 +0000486void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000487 Out << Decls.size() << " result(s)";
488 if (isAmbiguous()) Out << ", ambiguous";
489 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000490
John McCallf36e02d2009-10-09 21:13:30 +0000491 for (iterator I = begin(), E = end(); I != E; ++I) {
492 Out << "\n";
493 (*I)->print(Out, 2);
494 }
495}
496
Douglas Gregor85910982010-02-12 05:48:04 +0000497/// \brief Lookup a builtin function, when name lookup would otherwise
498/// fail.
499static bool LookupBuiltin(Sema &S, LookupResult &R) {
500 Sema::LookupNameKind NameKind = R.getLookupKind();
501
502 // If we didn't find a use of this identifier, and if the identifier
503 // corresponds to a compiler builtin, create the decl object for the builtin
504 // now, injecting it into translation unit scope, and return it.
505 if (NameKind == Sema::LookupOrdinaryName ||
506 NameKind == Sema::LookupRedeclarationWithLinkage) {
507 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
508 if (II) {
Nico Webercac18ad2013-06-20 21:44:55 +0000509 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
510 II == S.getFloat128Identifier()) {
511 // libstdc++4.7's type_traits expects type __float128 to exist, so
512 // insert a dummy type to make that header build in gnu++11 mode.
513 R.addDecl(S.getASTContext().getFloat128StubType());
514 return true;
515 }
516
Douglas Gregor85910982010-02-12 05:48:04 +0000517 // If this is a builtin on this (or all) targets, create the decl.
518 if (unsigned BuiltinID = II->getBuiltinID()) {
519 // In C++, we don't have any predefined library functions like
520 // 'malloc'. Instead, we'll just error.
David Blaikie4e4d0842012-03-11 07:00:24 +0000521 if (S.getLangOpts().CPlusPlus &&
Douglas Gregor85910982010-02-12 05:48:04 +0000522 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
523 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524
525 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
526 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000527 R.isForRedeclaration(),
528 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000529 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000530 return true;
531 }
532
533 if (R.isForRedeclaration()) {
534 // If we're redeclaring this function anyway, forget that
535 // this was a builtin at all.
536 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
537 }
538
539 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000540 }
541 }
542 }
543
544 return false;
545}
546
Douglas Gregor4923aa22010-07-02 20:37:36 +0000547/// \brief Determine whether we can declare a special member function within
548/// the class at this point.
Richard Smithd0adeb62012-11-27 21:20:31 +0000549static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +0000550 // We need to have a definition for the class.
551 if (!Class->getDefinition() || Class->isDependentContext())
552 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553
Douglas Gregor4923aa22010-07-02 20:37:36 +0000554 // We can't be in the middle of defining the class.
Richard Smithd0adeb62012-11-27 21:20:31 +0000555 return !Class->isBeingDefined();
Douglas Gregor4923aa22010-07-02 20:37:36 +0000556}
557
558void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000559 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregor22584312010-07-02 23:41:54 +0000560 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000561
562 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000563 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000564 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000565
Douglas Gregor22584312010-07-02 23:41:54 +0000566 // If the copy constructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000567 if (Class->needsImplicitCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +0000568 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000569
Douglas Gregora376d102010-07-02 21:50:04 +0000570 // If the copy assignment operator has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000571 if (Class->needsImplicitCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000572 DeclareImplicitCopyAssignment(Class);
573
Richard Smith80ad52f2013-01-02 11:42:31 +0000574 if (getLangOpts().CPlusPlus11) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000575 // If the move constructor has not yet been declared, do so now.
576 if (Class->needsImplicitMoveConstructor())
577 DeclareImplicitMoveConstructor(Class); // might not actually do it
578
579 // If the move assignment operator has not yet been declared, do so now.
580 if (Class->needsImplicitMoveAssignment())
581 DeclareImplicitMoveAssignment(Class); // might not actually do it
582 }
583
Douglas Gregor4923aa22010-07-02 20:37:36 +0000584 // If the destructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000585 if (Class->needsImplicitDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000587}
588
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000589/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000590/// special member function.
591static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
592 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000593 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000594 case DeclarationName::CXXDestructorName:
595 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000596
Douglas Gregora376d102010-07-02 21:50:04 +0000597 case DeclarationName::CXXOperatorName:
598 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599
Douglas Gregora376d102010-07-02 21:50:04 +0000600 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000602 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000603
Douglas Gregora376d102010-07-02 21:50:04 +0000604 return false;
605}
606
607/// \brief If there are any implicit member functions with the given name
608/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000610 DeclarationName Name,
611 const DeclContext *DC) {
612 if (!DC)
613 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000614
Douglas Gregora376d102010-07-02 21:50:04 +0000615 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000616 case DeclarationName::CXXConstructorName:
617 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithd0adeb62012-11-27 21:20:31 +0000618 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000619 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000620 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000621 S.DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +0000622 if (Record->needsImplicitCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000623 S.DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000624 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000625 Record->needsImplicitMoveConstructor())
626 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000627 }
Douglas Gregor22584312010-07-02 23:41:54 +0000628 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000629
Douglas Gregora376d102010-07-02 21:50:04 +0000630 case DeclarationName::CXXDestructorName:
631 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithe5411b72012-12-01 02:35:44 +0000632 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smithd0adeb62012-11-27 21:20:31 +0000633 CanDeclareSpecialMemberFunction(Record))
Douglas Gregora376d102010-07-02 21:50:04 +0000634 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000635 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000636
Douglas Gregora376d102010-07-02 21:50:04 +0000637 case DeclarationName::CXXOperatorName:
638 if (Name.getCXXOverloadedOperator() != OO_Equal)
639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000640
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000641 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000642 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000643 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smithe5411b72012-12-01 02:35:44 +0000644 if (Record->needsImplicitCopyAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000645 S.DeclareImplicitCopyAssignment(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000646 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000647 Record->needsImplicitMoveAssignment())
648 S.DeclareImplicitMoveAssignment(Class);
649 }
650 }
Douglas Gregora376d102010-07-02 21:50:04 +0000651 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652
Douglas Gregora376d102010-07-02 21:50:04 +0000653 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000654 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000655 }
656}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000657
John McCallf36e02d2009-10-09 21:13:30 +0000658// Adds all qualifying matches for a name within a decl context to the
659// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000660static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000661 bool Found = false;
662
Douglas Gregor4923aa22010-07-02 20:37:36 +0000663 // Lazily declare C++ special member functions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000664 if (S.getLangOpts().CPlusPlus)
Douglas Gregora376d102010-07-02 21:50:04 +0000665 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000666
Douglas Gregor4923aa22010-07-02 20:37:36 +0000667 // Perform lookup into this declaration context.
David Blaikie3bc93e32012-12-19 00:45:41 +0000668 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
669 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
670 ++I) {
John McCall46460a62010-01-20 21:53:11 +0000671 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000672 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000673 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000674 Found = true;
675 }
676 }
John McCallf36e02d2009-10-09 21:13:30 +0000677
Douglas Gregor85910982010-02-12 05:48:04 +0000678 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
679 return true;
680
Douglas Gregor48026d22010-01-11 18:40:55 +0000681 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000682 != DeclarationName::CXXConversionFunctionName ||
683 R.getLookupName().getCXXNameType()->isDependentType() ||
684 !isa<CXXRecordDecl>(DC))
685 return Found;
686
687 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000688 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000689 // name lookup. Instead, any conversion function templates visible in the
690 // context of the use are considered. [...]
691 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000692 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000693 return Found;
694
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +0000695 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
696 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000697 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
698 if (!ConvTemplate)
699 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000700
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000701 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000702 // add the conversion function template. When we deduce template
703 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000704 // type of the new declaration with the type of the function template.
705 if (R.isForRedeclaration()) {
706 R.addDecl(ConvTemplate);
707 Found = true;
708 continue;
709 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000710
Douglas Gregor48026d22010-01-11 18:40:55 +0000711 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000712 // [...] For each such operator, if argument deduction succeeds
713 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000714 // name lookup.
715 //
716 // When referencing a conversion function for any purpose other than
717 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000718 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000719 // specialization into the result set. We do this to avoid forcing all
720 // callers to perform special deduction for conversion functions.
Craig Topper93e45992012-09-19 02:26:47 +0000721 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000722 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000723
724 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000725 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
726 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000727
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000728 // Compute the type of the function that we would expect the conversion
729 // function to have, if it were to match the name given.
730 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000731 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
732 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000733 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000734 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000735 QualType ExpectedType
736 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko55431692013-05-05 00:41:58 +0000737 None, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000738
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000739 // Perform template argument deduction against the type that we would
740 // expect the function to have.
741 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
742 Specialization, Info)
743 == Sema::TDK_Success) {
744 R.addDecl(Specialization);
745 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000746 }
747 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000748
John McCallf36e02d2009-10-09 21:13:30 +0000749 return Found;
750}
751
John McCalld7be78a2009-11-10 07:01:13 +0000752// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000753static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000754CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000755 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000756
757 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
758
John McCalld7be78a2009-11-10 07:01:13 +0000759 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000760 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000761
John McCalld7be78a2009-11-10 07:01:13 +0000762 // Perform direct name lookup into the namespaces nominated by the
763 // using directives whose common ancestor is this namespace.
764 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
765 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000766
John McCalld7be78a2009-11-10 07:01:13 +0000767 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000768 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000769 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000770
771 R.resolveKind();
772
773 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000774}
775
776static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000777 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000778 return Ctx->isFileContext();
779 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000780}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000781
Douglas Gregor711be1e2010-03-15 14:33:29 +0000782// Find the next outer declaration context from this scope. This
783// routine actually returns the semantic outer context, which may
784// differ from the lexical context (encoded directly in the Scope
785// stack) when we are parsing a member of a class template. In this
786// case, the second element of the pair will be true, to indicate that
787// name lookup should continue searching in this semantic context when
788// it leaves the current template parameter scope.
789static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
790 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
791 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000792 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000793 OuterS = OuterS->getParent()) {
794 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000795 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000796 break;
797 }
798 }
799
800 // C++ [temp.local]p8:
801 // In the definition of a member of a class template that appears
802 // outside of the namespace containing the class template
803 // definition, the name of a template-parameter hides the name of
804 // a member of this namespace.
805 //
806 // Example:
807 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000808 // namespace N {
809 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000810 //
811 // template<class T> class B {
812 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000813 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000814 // }
815 //
816 // template<class C> void N::B<C>::f(C) {
817 // C b; // C is the template parameter, not N::C
818 // }
819 //
820 // In this example, the lexical context we return is the
821 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000822 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000823 !S->getParent()->isTemplateParamScope())
824 return std::make_pair(Lexical, false);
825
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000826 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000827 // For the example, this is the scope for the template parameters of
828 // template<class C>.
829 Scope *OutermostTemplateScope = S->getParent();
830 while (OutermostTemplateScope->getParent() &&
831 OutermostTemplateScope->getParent()->isTemplateParamScope())
832 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000833
Douglas Gregor711be1e2010-03-15 14:33:29 +0000834 // Find the namespace context in which the original scope occurs. In
835 // the example, this is namespace N.
836 DeclContext *Semantic = DC;
837 while (!Semantic->isFileContext())
838 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000839
Douglas Gregor711be1e2010-03-15 14:33:29 +0000840 // Find the declaration context just outside of the template
841 // parameter scope. This is the context in which the template is
842 // being lexically declaration (a namespace context). In the
843 // example, this is the global scope.
844 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
845 Lexical->Encloses(Semantic))
846 return std::make_pair(Semantic, true);
847
848 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000849}
850
John McCalla24dc2e2009-11-17 02:14:36 +0000851bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000852 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000853
854 DeclarationName Name = R.getLookupName();
Richard Smithdd9459f2013-08-13 18:18:50 +0000855 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCalla24dc2e2009-11-17 02:14:36 +0000856
Douglas Gregora376d102010-07-02 21:50:04 +0000857 // If this is the name of an implicitly-declared special member function,
858 // go through the scope stack to implicitly declare
859 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
860 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
861 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
862 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
863 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000864
Douglas Gregora376d102010-07-02 21:50:04 +0000865 // Implicitly declare member functions with the name we're looking for, if in
866 // fact we are in a scope where it matters.
867
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000868 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000869 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000870 I = IdResolver.begin(Name),
871 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000872
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000873 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000874 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000875 // ...During unqualified name lookup (3.4.1), the names appear as if
876 // they were declared in the nearest enclosing namespace which contains
877 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000878 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000879 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000880 //
881 // For example:
882 // namespace A { int i; }
883 // void foo() {
884 // int i;
885 // {
886 // using namespace A;
887 // ++i; // finds local 'i', A::i appears at global scope
888 // }
889 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000890 //
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000891 UnqualUsingDirectiveSet UDirs;
892 bool VisitedUsingDirectives = false;
Richard Smithdd9459f2013-08-13 18:18:50 +0000893 bool LeftStartingScope = false;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000894 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000895 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000896 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
897
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000898 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000899 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000900 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000901 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smithdd9459f2013-08-13 18:18:50 +0000902 if (NameKind == LookupRedeclarationWithLinkage) {
903 // Determine whether this (or a previous) declaration is
904 // out-of-scope.
905 if (!LeftStartingScope && !Initial->isDeclScope(*I))
906 LeftStartingScope = true;
907
908 // If we found something outside of our starting scope that
909 // does not have linkage, skip it.
910 if (LeftStartingScope && !((*I)->hasLinkage())) {
911 R.setShadowed();
912 continue;
913 }
914 }
915
John McCallf36e02d2009-10-09 21:13:30 +0000916 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000917 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000918 }
919 }
John McCallf36e02d2009-10-09 21:13:30 +0000920 if (Found) {
921 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000922 if (S->isClassScope())
923 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
924 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000925 return true;
926 }
927
Richard Smithdd9459f2013-08-13 18:18:50 +0000928 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith4e9686b2013-08-09 04:35:01 +0000929 // C++11 [class.friend]p11:
930 // If a friend declaration appears in a local class and the name
931 // specified is an unqualified name, a prior declaration is
932 // looked up without considering scopes that are outside the
933 // innermost enclosing non-class scope.
934 return false;
935 }
936
Douglas Gregor711be1e2010-03-15 14:33:29 +0000937 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
938 S->getParent() && !S->getParent()->isTemplateParamScope()) {
939 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000940 // found nothing, so look into the contexts between the
Douglas Gregor711be1e2010-03-15 14:33:29 +0000941 // lexical and semantic declaration contexts returned by
942 // findOuterContext(). This implements the name lookup behavior
943 // of C++ [temp.local]p8.
944 Ctx = OutsideOfTemplateParamDC;
945 OutsideOfTemplateParamDC = 0;
946 }
947
948 if (Ctx) {
949 DeclContext *OuterCtx;
950 bool SearchAfterTemplateScope;
951 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
952 if (SearchAfterTemplateScope)
953 OutsideOfTemplateParamDC = OuterCtx;
954
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000955 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000956 // We do not directly look into transparent contexts, since
957 // those entities will be found in the nearest enclosing
958 // non-transparent context.
959 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000960 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000961
962 // We do not look directly into function or method contexts,
963 // since all of the local variables and parameters of the
964 // function/method are present within the Scope.
965 if (Ctx->isFunctionOrMethod()) {
966 // If we have an Objective-C instance method, look for ivars
967 // in the corresponding interface.
968 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
969 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
970 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
971 ObjCInterfaceDecl *ClassDeclared;
972 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000973 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000974 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000975 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
976 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000977 R.resolveKind();
978 return true;
979 }
980 }
981 }
982 }
983
984 continue;
985 }
986
Douglas Gregor6bed88e2013-03-27 12:51:49 +0000987 // If this is a file context, we need to perform unqualified name
988 // lookup considering using directives.
989 if (Ctx->isFileContext()) {
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000990 // If we haven't handled using directives yet, do so now.
991 if (!VisitedUsingDirectives) {
992 // Add using directives from this context up to the top level.
Douglas Gregor34366202013-04-09 01:49:26 +0000993 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
994 if (UCtx->isTransparentContext())
995 continue;
996
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000997 UDirs.visit(UCtx, UCtx);
Douglas Gregor34366202013-04-09 01:49:26 +0000998 }
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000999
1000 // Find the innermost file scope, so we can add using directives
1001 // from local scopes.
1002 Scope *InnermostFileScope = S;
1003 while (InnermostFileScope &&
1004 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1005 InnermostFileScope = InnermostFileScope->getParent();
1006 UDirs.visitScopeChain(Initial, InnermostFileScope);
1007
1008 UDirs.done();
1009
1010 VisitedUsingDirectives = true;
1011 }
Douglas Gregor6bed88e2013-03-27 12:51:49 +00001012
1013 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1014 R.resolveKind();
1015 return true;
1016 }
1017
1018 continue;
1019 }
1020
Douglas Gregore942bbe2009-09-10 16:57:35 +00001021 // Perform qualified name lookup into this context.
1022 // FIXME: In some cases, we know that every name that could be found by
1023 // this qualified name lookup will also be on the identifier chain. For
1024 // example, inside a class without any base classes, we never need to
1025 // perform qualified lookup because all of the members are on top of the
1026 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001027 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +00001028 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +00001029 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001030 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001031 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001032
John McCalld7be78a2009-11-10 07:01:13 +00001033 // Stop if we ran out of scopes.
1034 // FIXME: This really, really shouldn't be happening.
1035 if (!S) return false;
1036
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001037 // If we are looking for members, no need to look into global/namespace scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00001038 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001039 return false;
1040
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001041 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001042 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +00001043 //
Mike Stump390b4cc2009-05-16 07:39:55 +00001044 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1045 // don't build it for each lookup!
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001046 if (!VisitedUsingDirectives) {
1047 UDirs.visitScopeChain(Initial, S);
1048 UDirs.done();
1049 }
1050
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001051 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001052 // Unqualified name lookup in C++ requires looking into scopes
1053 // that aren't strictly lexical, and therefore we walk through the
1054 // context as well as walking through the scopes.
1055 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001056 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +00001057 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +00001058 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +00001059 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001060 // We found something. Look for anything else in our scope
1061 // with this same name and in an acceptable identifier
1062 // namespace, so that we can construct an overload set if we
1063 // need to.
John McCallf36e02d2009-10-09 21:13:30 +00001064 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +00001065 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001066 }
1067 }
1068
Douglas Gregor00b4b032010-05-14 04:53:42 +00001069 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +00001070 R.resolveKind();
1071 return true;
1072 }
1073
Douglas Gregor00b4b032010-05-14 04:53:42 +00001074 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1075 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1076 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1077 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001078 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001079 // lexical and semantic declaration contexts returned by
1080 // findOuterContext(). This implements the name lookup behavior
1081 // of C++ [temp.local]p8.
1082 Ctx = OutsideOfTemplateParamDC;
1083 OutsideOfTemplateParamDC = 0;
1084 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
Douglas Gregor00b4b032010-05-14 04:53:42 +00001086 if (Ctx) {
1087 DeclContext *OuterCtx;
1088 bool SearchAfterTemplateScope;
1089 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1090 if (SearchAfterTemplateScope)
1091 OutsideOfTemplateParamDC = OuterCtx;
1092
1093 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1094 // We do not directly look into transparent contexts, since
1095 // those entities will be found in the nearest enclosing
1096 // non-transparent context.
1097 if (Ctx->isTransparentContext())
1098 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001099
Douglas Gregor00b4b032010-05-14 04:53:42 +00001100 // If we have a context, and it's not a context stashed in the
1101 // template parameter scope for an out-of-line definition, also
1102 // look into that context.
1103 if (!(Found && S && S->isTemplateParamScope())) {
1104 assert(Ctx->isFileContext() &&
1105 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001106
Douglas Gregor00b4b032010-05-14 04:53:42 +00001107 // Look into context considering using-directives.
1108 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1109 Found = true;
1110 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001111
Douglas Gregor00b4b032010-05-14 04:53:42 +00001112 if (Found) {
1113 R.resolveKind();
1114 return true;
1115 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001116
Douglas Gregor00b4b032010-05-14 04:53:42 +00001117 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1118 return false;
1119 }
1120 }
1121
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001122 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001123 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001124 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001125
John McCallf36e02d2009-10-09 21:13:30 +00001126 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001127}
1128
Richard Smithb7751002013-07-25 23:08:39 +00001129/// \brief Find the declaration that a class temploid member specialization was
1130/// instantiated from, or the member itself if it is an explicit specialization.
1131static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1132 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1133}
1134
1135/// \brief Find the module in which the given declaration was defined.
1136static Module *getDefiningModule(Decl *Entity) {
1137 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1138 // If this function was instantiated from a template, the defining module is
1139 // the module containing the pattern.
1140 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1141 Entity = Pattern;
1142 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1143 // If it's a class template specialization, find the template or partial
1144 // specialization from which it was instantiated.
1145 if (ClassTemplateSpecializationDecl *SpecRD =
1146 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1147 llvm::PointerUnion<ClassTemplateDecl*,
1148 ClassTemplatePartialSpecializationDecl*> From =
1149 SpecRD->getInstantiatedFrom();
1150 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1151 Entity = FromTemplate->getTemplatedDecl();
1152 else if (From)
1153 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1154 // Otherwise, it's an explicit specialization.
1155 } else if (MemberSpecializationInfo *MSInfo =
1156 RD->getMemberSpecializationInfo())
1157 Entity = getInstantiatedFrom(RD, MSInfo);
1158 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1159 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1160 Entity = getInstantiatedFrom(ED, MSInfo);
1161 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1162 // FIXME: Map from variable template specializations back to the template.
1163 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1164 Entity = getInstantiatedFrom(VD, MSInfo);
1165 }
1166
1167 // Walk up to the containing context. That might also have been instantiated
1168 // from a template.
1169 DeclContext *Context = Entity->getDeclContext();
1170 if (Context->isFileContext())
1171 return Entity->getOwningModule();
1172 return getDefiningModule(cast<Decl>(Context));
1173}
1174
1175llvm::DenseSet<Module*> &Sema::getLookupModules() {
1176 unsigned N = ActiveTemplateInstantiations.size();
1177 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1178 I != N; ++I) {
1179 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1180 if (M && !LookupModulesCache.insert(M).second)
1181 M = 0;
1182 ActiveTemplateInstantiationLookupModules.push_back(M);
1183 }
1184 return LookupModulesCache;
1185}
1186
1187/// \brief Determine whether a declaration is visible to name lookup.
1188///
1189/// This routine determines whether the declaration D is visible in the current
1190/// lookup context, taking into account the current template instantiation
1191/// stack. During template instantiation, a declaration is visible if it is
1192/// visible from a module containing any entity on the template instantiation
1193/// path (by instantiating a template, you allow it to see the declarations that
1194/// your module can see, including those later on in your module).
1195bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1196 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1197 "should not call this: not in slow case");
1198 Module *DeclModule = D->getOwningModule();
1199 assert(DeclModule && "hidden decl not from a module");
1200
1201 // Find the extra places where we need to look.
1202 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1203 if (LookupModules.empty())
1204 return false;
1205
1206 // If our lookup set contains the decl's module, it's visible.
1207 if (LookupModules.count(DeclModule))
1208 return true;
1209
1210 // If the declaration isn't exported, it's not visible in any other module.
1211 if (D->isModulePrivate())
1212 return false;
1213
1214 // Check whether DeclModule is transitively exported to an import of
1215 // the lookup set.
1216 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1217 E = LookupModules.end();
1218 I != E; ++I)
1219 if ((*I)->isModuleVisible(DeclModule))
1220 return true;
1221 return false;
1222}
1223
Douglas Gregor55368912011-12-14 16:03:29 +00001224/// \brief Retrieve the visible declaration corresponding to D, if any.
1225///
1226/// This routine determines whether the declaration D is visible in the current
1227/// module, with the current imports. If not, it checks whether any
1228/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smithb7751002013-07-25 23:08:39 +00001229///
Douglas Gregor55368912011-12-14 16:03:29 +00001230/// \returns D, or a visible previous declaration of D, whichever is more recent
1231/// and visible. If no declaration of D is visible, returns null.
Richard Smithd67679d2013-08-20 20:35:18 +00001232static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1233 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smithb7751002013-07-25 23:08:39 +00001234
Douglas Gregor0782ef22012-01-06 22:05:37 +00001235 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1236 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001237 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Richard Smithd67679d2013-08-20 20:35:18 +00001238 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor0782ef22012-01-06 22:05:37 +00001239 return ND;
1240 }
Douglas Gregor55368912011-12-14 16:03:29 +00001241 }
Richard Smithb7751002013-07-25 23:08:39 +00001242
Douglas Gregor55368912011-12-14 16:03:29 +00001243 return 0;
1244}
1245
Richard Smithd67679d2013-08-20 20:35:18 +00001246NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1247 return findAcceptableDecl(SemaRef, D);
1248}
1249
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001250/// @brief Perform unqualified name lookup starting from a given
1251/// scope.
1252///
1253/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1254/// used to find names within the current scope. For example, 'x' in
1255/// @code
1256/// int x;
1257/// int f() {
1258/// return x; // unqualified name look finds 'x' in the global scope
1259/// }
1260/// @endcode
1261///
1262/// Different lookup criteria can find different names. For example, a
1263/// particular scope can have both a struct and a function of the same
1264/// name, and each can be found by certain lookup criteria. For more
1265/// information about lookup criteria, see the documentation for the
1266/// class LookupCriteria.
1267///
1268/// @param S The scope from which unqualified name lookup will
1269/// begin. If the lookup criteria permits, name lookup may also search
1270/// in the parent scopes.
1271///
James Dennett8da16872012-06-22 10:32:46 +00001272/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1273/// look up and the lookup kind), and is updated with the results of lookup
1274/// including zero or more declarations and possibly additional information
1275/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001276///
James Dennett8da16872012-06-22 10:32:46 +00001277/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001278bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1279 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001280 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001281
John McCalla24dc2e2009-11-17 02:14:36 +00001282 LookupNameKind NameKind = R.getLookupKind();
1283
David Blaikie4e4d0842012-03-11 07:00:24 +00001284 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001285 // Unqualified name lookup in C/Objective-C is purely lexical, so
1286 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001287 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001288 // Find the nearest non-transparent declaration scope.
1289 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001290 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001291 static_cast<DeclContext *>(S->getEntity())
1292 ->isTransparentContext()))
1293 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001294 }
1295
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001296 // Scan up the scope chain looking for a decl that matches this
1297 // identifier that is in the appropriate namespace. This search
1298 // should not take long, as shadowing of names is uncommon, and
1299 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001300 bool LeftStartingScope = false;
1301
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001302 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001303 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001304 I != IEnd; ++I)
Richard Smithb7751002013-07-25 23:08:39 +00001305 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001306 if (NameKind == LookupRedeclarationWithLinkage) {
1307 // Determine whether this (or a previous) declaration is
1308 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001309 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001310 LeftStartingScope = true;
1311
1312 // If we found something outside of our starting scope that
1313 // does not have linkage, skip it.
Richard Smithdd9459f2013-08-13 18:18:50 +00001314 if (LeftStartingScope && !((*I)->hasLinkage())) {
1315 R.setShadowed();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001316 continue;
Richard Smithdd9459f2013-08-13 18:18:50 +00001317 }
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001318 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001319 else if (NameKind == LookupObjCImplicitSelfParam &&
1320 !isa<ImplicitParamDecl>(*I))
1321 continue;
Richard Smithb7751002013-07-25 23:08:39 +00001322
Douglas Gregor55368912011-12-14 16:03:29 +00001323 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001324
Douglas Gregor7a537402012-01-03 23:26:26 +00001325 // Check whether there are any other declarations with the same name
1326 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001327 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001328 // Find the scope in which this declaration was declared (if it
1329 // actually exists in a Scope).
1330 while (S && !S->isDeclScope(D))
1331 S = S->getParent();
1332
1333 // If the scope containing the declaration is the translation unit,
1334 // then we'll need to perform our checks based on the matching
1335 // DeclContexts rather than matching scopes.
1336 if (S && isNamespaceOrTranslationUnitScope(S))
1337 S = 0;
1338
1339 // Compute the DeclContext, if we need it.
1340 DeclContext *DC = 0;
1341 if (!S)
1342 DC = (*I)->getDeclContext()->getRedeclContext();
1343
Douglas Gregorda795b42012-01-04 16:44:10 +00001344 IdentifierResolver::iterator LastI = I;
1345 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001346 if (S) {
1347 // Match based on scope.
1348 if (!S->isDeclScope(*LastI))
1349 break;
1350 } else {
1351 // Match based on DeclContext.
1352 DeclContext *LastDC
1353 = (*LastI)->getDeclContext()->getRedeclContext();
1354 if (!LastDC->Equals(DC))
1355 break;
1356 }
Richard Smithb7751002013-07-25 23:08:39 +00001357
1358 // If the declaration is in the right namespace and visible, add it.
1359 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1360 R.addDecl(LastD);
Douglas Gregorda795b42012-01-04 16:44:10 +00001361 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001362
Douglas Gregorda795b42012-01-04 16:44:10 +00001363 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001364 }
John McCallf36e02d2009-10-09 21:13:30 +00001365 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001366 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001367 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001368 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001369 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001370 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001371 }
1372
1373 // If we didn't find a use of this identifier, and if the identifier
1374 // corresponds to a compiler builtin, create the decl object for the builtin
1375 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001376 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1377 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001378
Axel Naumannf8291a12011-02-24 16:47:47 +00001379 // If we didn't find a use of this identifier, the ExternalSource
1380 // may be able to handle the situation.
1381 // Note: some lookup failures are expected!
1382 // See e.g. R.isForRedeclaration().
1383 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001384}
1385
John McCall6e247262009-10-10 05:48:19 +00001386/// @brief Perform qualified name lookup in the namespaces nominated by
1387/// using directives by the given context.
1388///
1389/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001390/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001391/// (where X is the global namespace), let S be the set of all
1392/// declarations of m in X and in the transitive closure of all
1393/// namespaces nominated by using-directives in X and its used
1394/// namespaces, except that using-directives are ignored in any
1395/// namespace, including X, directly containing one or more
1396/// declarations of m. No namespace is searched more than once in
1397/// the lookup of a name. If S is the empty set, the program is
1398/// ill-formed. Otherwise, if S has exactly one member, or if the
1399/// context of the reference is a using-declaration
1400/// (namespace.udecl), S is the required set of declarations of
1401/// m. Otherwise if the use of m is not one that allows a unique
1402/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001403///
John McCall6e247262009-10-10 05:48:19 +00001404/// C++98 [namespace.qual]p5:
1405/// During the lookup of a qualified namespace member name, if the
1406/// lookup finds more than one declaration of the member, and if one
1407/// declaration introduces a class name or enumeration name and the
1408/// other declarations either introduce the same object, the same
1409/// enumerator or a set of functions, the non-type name hides the
1410/// class or enumeration name if and only if the declarations are
1411/// from the same namespace; otherwise (the declarations are from
1412/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001413static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001414 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001415 assert(StartDC->isFileContext() && "start context is not a file context");
1416
1417 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1418 DeclContext::udir_iterator E = StartDC->using_directives_end();
1419
1420 if (I == E) return false;
1421
1422 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001423 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001424 Visited.insert(StartDC);
1425
1426 // We have not yet looked into these namespaces, much less added
1427 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001428 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001429
1430 // We have already looked into the initial namespace; seed the queue
1431 // with its using-children.
1432 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001433 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001434 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001435 Queue.push_back(ND);
1436 }
1437
1438 // The easiest way to implement the restriction in [namespace.qual]p5
1439 // is to check whether any of the individual results found a tag
1440 // and, if so, to declare an ambiguity if the final result is not
1441 // a tag.
1442 bool FoundTag = false;
1443 bool FoundNonTag = false;
1444
John McCall7d384dd2009-11-18 07:57:50 +00001445 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001446
1447 bool Found = false;
1448 while (!Queue.empty()) {
1449 NamespaceDecl *ND = Queue.back();
1450 Queue.pop_back();
1451
1452 // We go through some convolutions here to avoid copying results
1453 // between LookupResults.
1454 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001455 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001456 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001457
1458 if (FoundDirect) {
1459 // First do any local hiding.
1460 DirectR.resolveKind();
1461
1462 // If the local result is a tag, remember that.
1463 if (DirectR.isSingleTagDecl())
1464 FoundTag = true;
1465 else
1466 FoundNonTag = true;
1467
1468 // Append the local results to the total results if necessary.
1469 if (UseLocal) {
1470 R.addAllDecls(LocalR);
1471 LocalR.clear();
1472 }
1473 }
1474
1475 // If we find names in this namespace, ignore its using directives.
1476 if (FoundDirect) {
1477 Found = true;
1478 continue;
1479 }
1480
1481 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1482 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001483 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001484 Queue.push_back(Nom);
1485 }
1486 }
1487
1488 if (Found) {
1489 if (FoundTag && FoundNonTag)
1490 R.setAmbiguousQualifiedTagHiding();
1491 else
1492 R.resolveKind();
1493 }
1494
1495 return Found;
1496}
1497
Douglas Gregor8071e422010-08-15 06:18:01 +00001498/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001499static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001500 CXXBasePath &Path,
1501 void *Name) {
1502 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001503
Douglas Gregor8071e422010-08-15 06:18:01 +00001504 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1505 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001506 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001507}
1508
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001509/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001510/// static members, nested types, and enumerators.
1511template<typename InputIterator>
1512static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1513 Decl *D = (*First)->getUnderlyingDecl();
1514 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1515 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001516
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001517 if (isa<CXXMethodDecl>(D)) {
1518 // Determine whether all of the methods are static.
1519 bool AllMethodsAreStatic = true;
1520 for(; First != Last; ++First) {
1521 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001522
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001523 if (!isa<CXXMethodDecl>(D)) {
1524 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1525 break;
1526 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001527
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001528 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1529 AllMethodsAreStatic = false;
1530 break;
1531 }
1532 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001533
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001534 if (AllMethodsAreStatic)
1535 return true;
1536 }
1537
1538 return false;
1539}
1540
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001541/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001542///
1543/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1544/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001545/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001546///
1547/// Different lookup criteria can find different names. For example, a
1548/// particular scope can have both a struct and a function of the same
1549/// name, and each can be found by certain lookup criteria. For more
1550/// information about lookup criteria, see the documentation for the
1551/// class LookupCriteria.
1552///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001553/// \param R captures both the lookup criteria and any lookup results found.
1554///
1555/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001556/// search. If the lookup criteria permits, name lookup may also search
1557/// in the parent contexts or (for C++ classes) base classes.
1558///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001559/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001560/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001561///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001562/// \returns true if lookup succeeded, false if it failed.
1563bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1564 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001565 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001566
John McCalla24dc2e2009-11-17 02:14:36 +00001567 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001568 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001570 // Make sure that the declaration context is complete.
1571 assert((!isa<TagDecl>(LookupCtx) ||
1572 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001573 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001574 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001575 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001577 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001578 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001579 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001580 if (isa<CXXRecordDecl>(LookupCtx))
1581 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001582 return true;
1583 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001584
John McCall6e247262009-10-10 05:48:19 +00001585 // Don't descend into implied contexts for redeclarations.
1586 // C++98 [namespace.qual]p6:
1587 // In a declaration for a namespace member in which the
1588 // declarator-id is a qualified-id, given that the qualified-id
1589 // for the namespace member has the form
1590 // nested-name-specifier unqualified-id
1591 // the unqualified-id shall name a member of the namespace
1592 // designated by the nested-name-specifier.
1593 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001594 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001595 return false;
1596
John McCalla24dc2e2009-11-17 02:14:36 +00001597 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001598 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001599 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001600
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001601 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001602 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001603 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001604 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001605 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001606
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001607 // If we're performing qualified name lookup into a dependent class,
1608 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001609 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001610 // template instantiation time (at which point all bases will be available)
1611 // or we have to fail.
1612 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1613 LookupRec->hasAnyDependentBases()) {
1614 R.setNotFoundInCurrentInstantiation();
1615 return false;
1616 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001617
Douglas Gregor7176fff2009-01-15 00:26:24 +00001618 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001619 CXXBasePaths Paths;
1620 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001621
1622 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001623 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001624 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001625 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001626 case LookupOrdinaryName:
1627 case LookupMemberName:
1628 case LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +00001629 case LookupLocalFriendName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001630 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1631 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001632
Douglas Gregora8f32e02009-10-06 17:59:45 +00001633 case LookupTagName:
1634 BaseCallback = &CXXRecordDecl::FindTagMember;
1635 break;
John McCall9f54ad42009-12-10 09:41:52 +00001636
Douglas Gregor8071e422010-08-15 06:18:01 +00001637 case LookupAnyName:
1638 BaseCallback = &LookupAnyMember;
1639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001640
John McCall9f54ad42009-12-10 09:41:52 +00001641 case LookupUsingDeclName:
1642 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001643
Douglas Gregora8f32e02009-10-06 17:59:45 +00001644 case LookupOperatorName:
1645 case LookupNamespaceName:
1646 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001647 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001648 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001649 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650
Douglas Gregora8f32e02009-10-06 17:59:45 +00001651 case LookupNestedNameSpecifierName:
1652 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1653 break;
1654 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001655
John McCalla24dc2e2009-11-17 02:14:36 +00001656 if (!LookupRec->lookupInBases(BaseCallback,
1657 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001658 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001659
John McCall92f88312010-01-23 00:46:32 +00001660 R.setNamingClass(LookupRec);
1661
Douglas Gregor7176fff2009-01-15 00:26:24 +00001662 // C++ [class.member.lookup]p2:
1663 // [...] If the resulting set of declarations are not all from
1664 // sub-objects of the same type, or the set has a nonstatic member
1665 // and includes members from distinct sub-objects, there is an
1666 // ambiguity and the program is ill-formed. Otherwise that set is
1667 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001668 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001669 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001670 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001671
Douglas Gregora8f32e02009-10-06 17:59:45 +00001672 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001673 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001674 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001675
John McCall46460a62010-01-20 21:53:11 +00001676 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1677 // across all paths.
1678 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001679
Douglas Gregor7176fff2009-01-15 00:26:24 +00001680 // Determine whether we're looking at a distinct sub-object or not.
1681 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001682 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001683 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1684 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001685 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001686 }
1687
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001688 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001689 != Context.getCanonicalType(PathElement.Base->getType())) {
1690 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001691 // different types. If the declaration sets aren't the same, this
1692 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001693 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001694 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001695 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1696 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001697
David Blaikie3bc93e32012-12-19 00:45:41 +00001698 while (FirstD != FirstPath->Decls.end() &&
1699 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001700 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1701 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1702 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001703
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001704 ++FirstD;
1705 ++CurrentD;
1706 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001707
David Blaikie3bc93e32012-12-19 00:45:41 +00001708 if (FirstD == FirstPath->Decls.end() &&
1709 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001710 continue;
1711 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001712
John McCallf36e02d2009-10-09 21:13:30 +00001713 R.setAmbiguousBaseSubobjectTypes(Paths);
1714 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001715 }
1716
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001717 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001718 // We have a different subobject of the same type.
1719
1720 // C++ [class.member.lookup]p5:
1721 // A static member, a nested type or an enumerator defined in
1722 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001723 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001724 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001725 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001726
Douglas Gregor7176fff2009-01-15 00:26:24 +00001727 // We have found a nonstatic member name in multiple, distinct
1728 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001729 R.setAmbiguousBaseSubobjects(Paths);
1730 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001731 }
1732 }
1733
1734 // Lookup in a base class succeeded; return these results.
1735
David Blaikie3bc93e32012-12-19 00:45:41 +00001736 DeclContext::lookup_result DR = Paths.front().Decls;
1737 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001738 NamedDecl *D = *I;
1739 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1740 D->getAccess());
1741 R.addDecl(D, AS);
1742 }
John McCallf36e02d2009-10-09 21:13:30 +00001743 R.resolveKind();
1744 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001745}
1746
1747/// @brief Performs name lookup for a name that was parsed in the
1748/// source code, and may contain a C++ scope specifier.
1749///
1750/// This routine is a convenience routine meant to be called from
1751/// contexts that receive a name and an optional C++ scope specifier
1752/// (e.g., "N::M::x"). It will then perform either qualified or
1753/// unqualified name lookup (with LookupQualifiedName or LookupName,
1754/// respectively) on the given name and return those results.
1755///
1756/// @param S The scope from which unqualified name lookup will
1757/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001758///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001759/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001760///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001761/// @param EnteringContext Indicates whether we are going to enter the
1762/// context of the scope-specifier SS (if present).
1763///
John McCallf36e02d2009-10-09 21:13:30 +00001764/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001765bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001766 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001767 if (SS && SS->isInvalid()) {
1768 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001769 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001770 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001771 }
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Douglas Gregor495c35d2009-08-25 22:51:20 +00001773 if (SS && SS->isSet()) {
1774 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001775 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001776 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001777 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001778 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001779
John McCalla24dc2e2009-11-17 02:14:36 +00001780 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001781 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001782 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001783
Douglas Gregor495c35d2009-08-25 22:51:20 +00001784 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001785 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001786 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001787 R.setNotFoundInCurrentInstantiation();
1788 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001789 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001790 }
1791
Mike Stump1eb44332009-09-09 15:08:12 +00001792 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001793 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001794}
1795
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001796
James Dennett16ae9de2012-06-22 10:16:05 +00001797/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001798/// from name lookup.
1799///
James Dennett16ae9de2012-06-22 10:16:05 +00001800/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump1eb44332009-09-09 15:08:12 +00001801///
James Dennett16ae9de2012-06-22 10:16:05 +00001802/// \returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001803bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001804 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1805
John McCalla24dc2e2009-11-17 02:14:36 +00001806 DeclarationName Name = Result.getLookupName();
1807 SourceLocation NameLoc = Result.getNameLoc();
1808 SourceRange LookupRange = Result.getContextRange();
1809
John McCall6e247262009-10-10 05:48:19 +00001810 switch (Result.getAmbiguityKind()) {
1811 case LookupResult::AmbiguousBaseSubobjects: {
1812 CXXBasePaths *Paths = Result.getBasePaths();
1813 QualType SubobjectType = Paths->front().back().Base->getType();
1814 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1815 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1816 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001817
David Blaikie3bc93e32012-12-19 00:45:41 +00001818 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001819 while (isa<CXXMethodDecl>(*Found) &&
1820 cast<CXXMethodDecl>(*Found)->isStatic())
1821 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001822
John McCall6e247262009-10-10 05:48:19 +00001823 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001824
John McCall6e247262009-10-10 05:48:19 +00001825 return true;
1826 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001827
John McCall6e247262009-10-10 05:48:19 +00001828 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001829 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1830 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001831
John McCall6e247262009-10-10 05:48:19 +00001832 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001833 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001834 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1835 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001836 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001837 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001838 if (DeclsPrinted.insert(D).second)
1839 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1840 }
1841
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001842 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001843 }
1844
John McCall6e247262009-10-10 05:48:19 +00001845 case LookupResult::AmbiguousTagHiding: {
1846 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001847
John McCall6e247262009-10-10 05:48:19 +00001848 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1849
1850 LookupResult::iterator DI, DE = Result.end();
1851 for (DI = Result.begin(); DI != DE; ++DI)
1852 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1853 TagDecls.insert(TD);
1854 Diag(TD->getLocation(), diag::note_hidden_tag);
1855 }
1856
1857 for (DI = Result.begin(); DI != DE; ++DI)
1858 if (!isa<TagDecl>(*DI))
1859 Diag((*DI)->getLocation(), diag::note_hiding_object);
1860
1861 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001862 LookupResult::Filter F = Result.makeFilter();
1863 while (F.hasNext()) {
1864 if (TagDecls.count(F.next()))
1865 F.erase();
1866 }
1867 F.done();
John McCall6e247262009-10-10 05:48:19 +00001868
1869 return true;
1870 }
1871
1872 case LookupResult::AmbiguousReference: {
1873 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001874
John McCall6e247262009-10-10 05:48:19 +00001875 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1876 for (; DI != DE; ++DI)
1877 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001878
John McCall6e247262009-10-10 05:48:19 +00001879 return true;
1880 }
1881 }
1882
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001883 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001884}
Douglas Gregorfa047642009-02-04 00:32:51 +00001885
John McCallc7e04da2010-05-28 18:45:08 +00001886namespace {
1887 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001888 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001889 Sema::AssociatedNamespaceSet &Namespaces,
1890 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001891 : S(S), Namespaces(Namespaces), Classes(Classes),
1892 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001893 }
1894
1895 Sema &S;
1896 Sema::AssociatedNamespaceSet &Namespaces;
1897 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001898 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001899 };
1900}
1901
Mike Stump1eb44332009-09-09 15:08:12 +00001902static void
John McCallc7e04da2010-05-28 18:45:08 +00001903addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001904
Douglas Gregor54022952010-04-30 07:08:38 +00001905static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1906 DeclContext *Ctx) {
1907 // Add the associated namespace for this class.
1908
1909 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1910 // be a locally scoped record.
1911
Sebastian Redl410c4f22010-08-31 20:53:31 +00001912 // We skip out of inline namespaces. The innermost non-inline namespace
1913 // contains all names of all its nested inline namespaces anyway, so we can
1914 // replace the entire inline namespace tree with its root.
1915 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1916 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001917 Ctx = Ctx->getParent();
1918
John McCall6ff07852009-08-07 22:18:02 +00001919 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001920 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001921}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001922
Mike Stump1eb44332009-09-09 15:08:12 +00001923// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001924// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001925static void
John McCallc7e04da2010-05-28 18:45:08 +00001926addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1927 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001928 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001929 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001930 switch (Arg.getKind()) {
1931 case TemplateArgument::Null:
1932 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Douglas Gregor69be8d62009-07-08 07:51:57 +00001934 case TemplateArgument::Type:
1935 // [...] the namespaces and classes associated with the types of the
1936 // template arguments provided for template type parameters (excluding
1937 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001938 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001939 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001940
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001941 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001942 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001943 // [...] the namespaces in which any template template arguments are
1944 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001945 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001946 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001947 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001948 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001949 DeclContext *Ctx = ClassTemplate->getDeclContext();
1950 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001951 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001952 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001953 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001954 }
1955 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001956 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001957
Douglas Gregor788cd062009-11-11 01:00:40 +00001958 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001959 case TemplateArgument::Integral:
1960 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001961 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001962 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001963 // associated namespaces. ]
1964 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Douglas Gregor69be8d62009-07-08 07:51:57 +00001966 case TemplateArgument::Pack:
1967 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1968 PEnd = Arg.pack_end();
1969 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001970 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001971 break;
1972 }
1973}
1974
Douglas Gregorfa047642009-02-04 00:32:51 +00001975// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001976// argument-dependent lookup with an argument of class type
1977// (C++ [basic.lookup.koenig]p2).
1978static void
John McCallc7e04da2010-05-28 18:45:08 +00001979addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1980 CXXRecordDecl *Class) {
1981
1982 // Just silently ignore anything whose name is __va_list_tag.
1983 if (Class->getDeclName() == Result.S.VAListTagName)
1984 return;
1985
Douglas Gregorfa047642009-02-04 00:32:51 +00001986 // C++ [basic.lookup.koenig]p2:
1987 // [...]
1988 // -- If T is a class type (including unions), its associated
1989 // classes are: the class itself; the class of which it is a
1990 // member, if any; and its direct and indirect base
1991 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001992 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001993
1994 // Add the class of which it is a member, if any.
1995 DeclContext *Ctx = Class->getDeclContext();
1996 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001997 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001998 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001999 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Douglas Gregorfa047642009-02-04 00:32:51 +00002001 // Add the class itself. If we've already seen this class, we don't
2002 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00002003 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00002004 return;
2005
Mike Stump1eb44332009-09-09 15:08:12 +00002006 // -- If T is a template-id, its associated namespaces and classes are
2007 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002008 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00002009 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00002010 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00002011 // namespaces in which any template template arguments are defined; and
2012 // the classes in which any member templates used as template template
2013 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00002014 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00002015 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00002016 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2017 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2018 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002019 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002020 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002021 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Douglas Gregor69be8d62009-07-08 07:51:57 +00002023 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2024 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00002025 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
John McCall86ff3082010-02-04 22:26:26 +00002028 // Only recurse into base classes for complete types.
2029 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00002030 QualType type = Result.S.Context.getTypeDeclType(Class);
2031 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
2032 /*no diagnostic*/ 0))
2033 return;
John McCall86ff3082010-02-04 22:26:26 +00002034 }
2035
Douglas Gregorfa047642009-02-04 00:32:51 +00002036 // Add direct and indirect base classes along with their associated
2037 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002038 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00002039 Bases.push_back(Class);
2040 while (!Bases.empty()) {
2041 // Pop this class off the stack.
2042 Class = Bases.back();
2043 Bases.pop_back();
2044
2045 // Visit the base classes.
2046 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
2047 BaseEnd = Class->bases_end();
2048 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002049 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00002050 // In dependent contexts, we do ADL twice, and the first time around,
2051 // the base type might be a dependent TemplateSpecializationType, or a
2052 // TemplateTypeParmType. If that happens, simply ignore it.
2053 // FIXME: If we want to support export, we probably need to add the
2054 // namespace of the template in a TemplateSpecializationType, or even
2055 // the classes and namespaces of known non-dependent arguments.
2056 if (!BaseType)
2057 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002058 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002059 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002060 // Find the associated namespace for this base class.
2061 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00002062 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002063
2064 // Make sure we visit the bases of this base class.
2065 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2066 Bases.push_back(BaseDecl);
2067 }
2068 }
2069 }
2070}
2071
2072// \brief Add the associated classes and namespaces for
2073// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00002074// (C++ [basic.lookup.koenig]p2).
2075static void
John McCallc7e04da2010-05-28 18:45:08 +00002076addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002077 // C++ [basic.lookup.koenig]p2:
2078 //
2079 // For each argument type T in the function call, there is a set
2080 // of zero or more associated namespaces and a set of zero or more
2081 // associated classes to be considered. The sets of namespaces and
2082 // classes is determined entirely by the types of the function
2083 // arguments (and the namespace of any template template
2084 // argument). Typedef names and using-declarations used to specify
2085 // the types do not contribute to this set. The sets of namespaces
2086 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00002087
Chris Lattner5f9e2722011-07-23 10:55:15 +00002088 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00002089 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2090
Douglas Gregorfa047642009-02-04 00:32:51 +00002091 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00002092 switch (T->getTypeClass()) {
2093
2094#define TYPE(Class, Base)
2095#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2096#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2097#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2098#define ABSTRACT_TYPE(Class, Base)
2099#include "clang/AST/TypeNodes.def"
2100 // T is canonical. We can also ignore dependent types because
2101 // we don't need to do ADL at the definition point, but if we
2102 // wanted to implement template export (or if we find some other
2103 // use for associated classes and namespaces...) this would be
2104 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00002105 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002106
John McCallfa4edcf2010-05-28 06:08:54 +00002107 // -- If T is a pointer to U or an array of U, its associated
2108 // namespaces and classes are those associated with U.
2109 case Type::Pointer:
2110 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2111 continue;
2112 case Type::ConstantArray:
2113 case Type::IncompleteArray:
2114 case Type::VariableArray:
2115 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2116 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002117
John McCallfa4edcf2010-05-28 06:08:54 +00002118 // -- If T is a fundamental type, its associated sets of
2119 // namespaces and classes are both empty.
2120 case Type::Builtin:
2121 break;
2122
2123 // -- If T is a class type (including unions), its associated
2124 // classes are: the class itself; the class of which it is a
2125 // member, if any; and its direct and indirect base
2126 // classes. Its associated namespaces are the namespaces in
2127 // which its associated classes are defined.
2128 case Type::Record: {
2129 CXXRecordDecl *Class
2130 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002131 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00002132 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002133 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00002134
John McCallfa4edcf2010-05-28 06:08:54 +00002135 // -- If T is an enumeration type, its associated namespace is
2136 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002137 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00002138 // it has no associated class.
2139 case Type::Enum: {
2140 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002141
John McCallfa4edcf2010-05-28 06:08:54 +00002142 DeclContext *Ctx = Enum->getDeclContext();
2143 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002144 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002145
John McCallfa4edcf2010-05-28 06:08:54 +00002146 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002147 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002148
John McCallfa4edcf2010-05-28 06:08:54 +00002149 break;
2150 }
2151
2152 // -- If T is a function type, its associated namespaces and
2153 // classes are those associated with the function parameter
2154 // types and those associated with the return type.
2155 case Type::FunctionProto: {
2156 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2157 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2158 ArgEnd = Proto->arg_type_end();
2159 Arg != ArgEnd; ++Arg)
2160 Queue.push_back(Arg->getTypePtr());
2161 // fallthrough
2162 }
2163 case Type::FunctionNoProto: {
2164 const FunctionType *FnType = cast<FunctionType>(T);
2165 T = FnType->getResultType().getTypePtr();
2166 continue;
2167 }
2168
2169 // -- If T is a pointer to a member function of a class X, its
2170 // associated namespaces and classes are those associated
2171 // with the function parameter types and return type,
2172 // together with those associated with X.
2173 //
2174 // -- If T is a pointer to a data member of class X, its
2175 // associated namespaces and classes are those associated
2176 // with the member type together with those associated with
2177 // X.
2178 case Type::MemberPointer: {
2179 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2180
2181 // Queue up the class type into which this points.
2182 Queue.push_back(MemberPtr->getClass());
2183
2184 // And directly continue with the pointee type.
2185 T = MemberPtr->getPointeeType().getTypePtr();
2186 continue;
2187 }
2188
2189 // As an extension, treat this like a normal pointer.
2190 case Type::BlockPointer:
2191 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2192 continue;
2193
2194 // References aren't covered by the standard, but that's such an
2195 // obvious defect that we cover them anyway.
2196 case Type::LValueReference:
2197 case Type::RValueReference:
2198 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2199 continue;
2200
2201 // These are fundamental types.
2202 case Type::Vector:
2203 case Type::ExtVector:
2204 case Type::Complex:
2205 break;
2206
Richard Smithdc7a4f52013-04-30 13:56:41 +00002207 // Non-deduced auto types only get here for error cases.
2208 case Type::Auto:
2209 break;
2210
Douglas Gregorf25760e2011-04-12 01:02:45 +00002211 // If T is an Objective-C object or interface type, or a pointer to an
2212 // object or interface type, the associated namespace is the global
2213 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002214 case Type::ObjCObject:
2215 case Type::ObjCInterface:
2216 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002217 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002218 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002219
2220 // Atomic types are just wrappers; use the associations of the
2221 // contained type.
2222 case Type::Atomic:
2223 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2224 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002225 }
2226
2227 if (Queue.empty()) break;
2228 T = Queue.back();
2229 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002230 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002231}
2232
2233/// \brief Find the associated classes and namespaces for
2234/// argument-dependent lookup for a call with the given set of
2235/// arguments.
2236///
2237/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002238/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002239/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm834c0582013-08-09 18:02:13 +00002240void Sema::FindAssociatedClassesAndNamespaces(
2241 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2242 AssociatedNamespaceSet &AssociatedNamespaces,
2243 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002244 AssociatedNamespaces.clear();
2245 AssociatedClasses.clear();
2246
John McCall42f48fb2012-08-24 20:38:34 +00002247 AssociatedLookup Result(*this, InstantiationLoc,
2248 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002249
Douglas Gregorfa047642009-02-04 00:32:51 +00002250 // C++ [basic.lookup.koenig]p2:
2251 // For each argument type T in the function call, there is a set
2252 // of zero or more associated namespaces and a set of zero or more
2253 // associated classes to be considered. The sets of namespaces and
2254 // classes is determined entirely by the types of the function
2255 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002256 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002257 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002258 Expr *Arg = Args[ArgIdx];
2259
2260 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002261 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002262 continue;
2263 }
2264
2265 // [...] In addition, if the argument is the name or address of a
2266 // set of overloaded functions and/or function templates, its
2267 // associated classes and namespaces are the union of those
2268 // associated with each of the members of the set: the namespace
2269 // in which the function or function template is defined and the
2270 // classes and namespaces associated with its (non-dependent)
2271 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002272 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002273 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002274 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002275 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002276
John McCallc7e04da2010-05-28 18:45:08 +00002277 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2278 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002279
John McCallc7e04da2010-05-28 18:45:08 +00002280 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2281 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002282 // Look through any using declarations to find the underlying function.
2283 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002284
Chandler Carruthbd647292009-12-29 06:17:27 +00002285 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2286 if (!FDecl)
2287 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002288
2289 // Add the classes and namespaces associated with the parameter
2290 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002291 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002292 }
2293 }
2294}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002295
2296/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2297/// an acceptable non-member overloaded operator for a call whose
2298/// arguments have types T1 (and, if non-empty, T2). This routine
2299/// implements the check in C++ [over.match.oper]p3b2 concerning
2300/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002301static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002302IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2303 QualType T1, QualType T2,
2304 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002305 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2306 return true;
2307
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002308 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2309 return true;
2310
John McCall183700f2009-09-21 23:43:11 +00002311 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002312 if (Proto->getNumArgs() < 1)
2313 return false;
2314
2315 if (T1->isEnumeralType()) {
2316 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002317 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002318 return true;
2319 }
2320
2321 if (Proto->getNumArgs() < 2)
2322 return false;
2323
2324 if (!T2.isNull() && T2->isEnumeralType()) {
2325 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002326 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002327 return true;
2328 }
2329
2330 return false;
2331}
2332
John McCall7d384dd2009-11-18 07:57:50 +00002333NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002334 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002335 LookupNameKind NameKind,
2336 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002337 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002338 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002339 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002340}
2341
Douglas Gregor6e378de2009-04-23 23:18:26 +00002342/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002343ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002344 SourceLocation IdLoc,
2345 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002346 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002347 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002348 return cast_or_null<ObjCProtocolDecl>(D);
2349}
2350
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002351void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002352 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002353 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002354 // C++ [over.match.oper]p3:
2355 // -- The set of non-member candidates is the result of the
2356 // unqualified lookup of operator@ in the context of the
2357 // expression according to the usual rules for name lookup in
2358 // unqualified function calls (3.4.2) except that all member
2359 // functions are ignored. However, if no operand has a class
2360 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002361 // that have a first parameter of type T1 or "reference to
2362 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002363 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002364 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002365 // when T2 is an enumeration type, are candidate functions.
2366 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002367 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2368 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002370 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2371
John McCallf36e02d2009-10-09 21:13:30 +00002372 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002373 return;
2374
2375 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2376 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002377 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2378 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002379 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002380 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002381 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002382 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002383 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002384 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002385 // later?
2386 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002387 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002388 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002389 }
2390}
2391
Sean Huntc39b6bc2011-06-24 02:11:39 +00002392Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002393 CXXSpecialMember SM,
2394 bool ConstArg,
2395 bool VolatileArg,
2396 bool RValueThis,
2397 bool ConstThis,
2398 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002399 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002400 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002401 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002402 if (RValueThis || ConstThis || VolatileThis)
2403 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2404 "constructors and destructors always have unqualified lvalue this");
2405 if (ConstArg || VolatileArg)
2406 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2407 "parameter-less special members can't have qualified arguments");
2408
2409 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002410 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002411 ID.AddInteger(SM);
2412 ID.AddInteger(ConstArg);
2413 ID.AddInteger(VolatileArg);
2414 ID.AddInteger(RValueThis);
2415 ID.AddInteger(ConstThis);
2416 ID.AddInteger(VolatileThis);
2417
2418 void *InsertPoint;
2419 SpecialMemberOverloadResult *Result =
2420 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2421
2422 // This was already cached
2423 if (Result)
2424 return Result;
2425
Sean Hunt30543582011-06-07 00:11:58 +00002426 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2427 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002428 SpecialMemberCache.InsertNode(Result, InsertPoint);
2429
2430 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002431 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002432 DeclareImplicitDestructor(RD);
2433 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002434 assert(DD && "record without a destructor");
2435 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002436 Result->setKind(DD->isDeleted() ?
2437 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002438 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002439 return Result;
2440 }
2441
Sean Huntb320e0c2011-06-10 03:50:41 +00002442 // Prepare for overload resolution. Here we construct a synthetic argument
2443 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002444 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002445 DeclarationName Name;
2446 Expr *Arg = 0;
2447 unsigned NumArgs;
2448
Richard Smith704c8f72012-04-20 18:46:14 +00002449 QualType ArgType = CanTy;
2450 ExprValueKind VK = VK_LValue;
2451
Sean Huntb320e0c2011-06-10 03:50:41 +00002452 if (SM == CXXDefaultConstructor) {
2453 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2454 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002455 if (RD->needsImplicitDefaultConstructor())
2456 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002457 } else {
2458 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2459 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002460 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002461 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002462 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002463 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002464 } else {
2465 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002466 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002467 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002468 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002469 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002470 }
2471
Sean Huntb320e0c2011-06-10 03:50:41 +00002472 if (ConstArg)
2473 ArgType.addConst();
2474 if (VolatileArg)
2475 ArgType.addVolatile();
2476
2477 // This isn't /really/ specified by the standard, but it's implied
2478 // we should be working from an RValue in the case of move to ensure
2479 // that we prefer to bind to rvalue references, and an LValue in the
2480 // case of copy to ensure we don't bind to rvalue references.
2481 // Possibly an XValue is actually correct in the case of move, but
2482 // there is no semantic difference for class types in this restricted
2483 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002484 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002485 VK = VK_LValue;
2486 else
2487 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002488 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002489
Richard Smith704c8f72012-04-20 18:46:14 +00002490 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2491
2492 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002493 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002494 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002495 }
2496
2497 // Create the object argument
2498 QualType ThisTy = CanTy;
2499 if (ConstThis)
2500 ThisTy.addConst();
2501 if (VolatileThis)
2502 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002503 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002504 OpaqueValueExpr(SourceLocation(), ThisTy,
2505 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002506
2507 // Now we perform lookup on the name we computed earlier and do overload
2508 // resolution. Lookup is only performed directly into the class since there
2509 // will always be a (possibly implicit) declaration to shadow any others.
2510 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002511 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00002512 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002513 "lookup for a constructor or assignment operator was empty");
Chandler Carruthab4e0c02013-08-18 07:20:52 +00002514
2515 // Copy the candidates as our processing of them may load new declarations
2516 // from an external source and invalidate lookup_result.
2517 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2518
2519 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
2520 E = Candidates.end();
2521 I != E; ++I) {
2522 NamedDecl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002523
Sean Huntc39b6bc2011-06-24 02:11:39 +00002524 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002525 continue;
2526
Sean Huntc39b6bc2011-06-24 02:11:39 +00002527 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2528 // FIXME: [namespace.udecl]p15 says that we should only consider a
2529 // using declaration here if it does not match a declaration in the
2530 // derived class. We do not implement this correctly in other cases
2531 // either.
2532 Cand = U->getTargetDecl();
2533
2534 if (Cand->isInvalidDecl())
2535 continue;
2536 }
2537
2538 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002539 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002540 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002541 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2542 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002543 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002544 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2545 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002546 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002547 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002548 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2549 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002550 RD, 0, ThisTy, Classification,
2551 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002552 OCS, true);
2553 else
2554 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002555 0, llvm::makeArrayRef(&Arg, NumArgs),
2556 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002557 } else {
2558 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002559 }
2560 }
2561
2562 OverloadCandidateSet::iterator Best;
2563 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2564 case OR_Success:
2565 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002566 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002567 break;
2568
2569 case OR_Deleted:
2570 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002571 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002572 break;
2573
2574 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002575 Result->setMethod(0);
2576 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2577 break;
2578
Sean Huntb320e0c2011-06-10 03:50:41 +00002579 case OR_No_Viable_Function:
2580 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002581 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002582 break;
2583 }
2584
2585 return Result;
2586}
2587
2588/// \brief Look up the default constructor for the given class.
2589CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002590 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002591 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2592 false, false);
2593
2594 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002595}
2596
Sean Hunt661c67a2011-06-21 23:42:56 +00002597/// \brief Look up the copying constructor for the given class.
2598CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002599 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002600 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2601 "non-const, non-volatile qualifiers for copy ctor arg");
2602 SpecialMemberOverloadResult *Result =
2603 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2604 Quals & Qualifiers::Volatile, false, false, false);
2605
Sean Huntc530d172011-06-10 04:44:37 +00002606 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2607}
2608
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002609/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002610CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2611 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002612 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002613 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2614 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002615
2616 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2617}
2618
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002619/// \brief Look up the constructors for the given class.
2620DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002621 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002622 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002623 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002624 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002625 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002626 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002627 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002628 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002629 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002630
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002631 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2632 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2633 return Class->lookup(Name);
2634}
2635
Sean Hunt661c67a2011-06-21 23:42:56 +00002636/// \brief Look up the copying assignment operator for the given class.
2637CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2638 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002639 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002640 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2641 "non-const, non-volatile qualifiers for copy assignment arg");
2642 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2643 "non-const, non-volatile qualifiers for copy assignment this");
2644 SpecialMemberOverloadResult *Result =
2645 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2646 Quals & Qualifiers::Volatile, RValueThis,
2647 ThisQuals & Qualifiers::Const,
2648 ThisQuals & Qualifiers::Volatile);
2649
Sean Hunt661c67a2011-06-21 23:42:56 +00002650 return Result->getMethod();
2651}
2652
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002653/// \brief Look up the moving assignment operator for the given class.
2654CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002655 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002656 bool RValueThis,
2657 unsigned ThisQuals) {
2658 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2659 "non-const, non-volatile qualifiers for copy assignment this");
2660 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002661 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2662 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002663 ThisQuals & Qualifiers::Const,
2664 ThisQuals & Qualifiers::Volatile);
2665
2666 return Result->getMethod();
2667}
2668
Douglas Gregordb89f282010-07-01 22:47:18 +00002669/// \brief Look for the destructor of the given class.
2670///
Sean Huntc5c9b532011-06-03 21:10:40 +00002671/// During semantic analysis, this routine should be used in lieu of
2672/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002673///
2674/// \returns The destructor for this class.
2675CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002676 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2677 false, false, false,
2678 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002679}
2680
Richard Smith36f5cfe2012-03-09 08:00:36 +00002681/// LookupLiteralOperator - Determine which literal operator should be used for
2682/// a user-defined literal, per C++11 [lex.ext].
2683///
2684/// Normal overload resolution is not used to select which literal operator to
2685/// call for a user-defined literal. Look up the provided literal operator name,
2686/// and filter the results to the appropriate set for the given argument types.
2687Sema::LiteralOperatorLookupResult
2688Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2689 ArrayRef<QualType> ArgTys,
2690 bool AllowRawAndTemplate) {
2691 LookupName(R, S);
2692 assert(R.getResultKind() != LookupResult::Ambiguous &&
2693 "literal operator lookup can't be ambiguous");
2694
2695 // Filter the lookup results appropriately.
2696 LookupResult::Filter F = R.makeFilter();
2697
2698 bool FoundTemplate = false;
2699 bool FoundRaw = false;
2700 bool FoundExactMatch = false;
2701
2702 while (F.hasNext()) {
2703 Decl *D = F.next();
2704 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2705 D = USD->getTargetDecl();
2706
2707 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2708 bool IsRaw = false;
2709 bool IsExactMatch = false;
2710
Douglas Gregor7e0c2272013-04-10 05:18:00 +00002711 // If the declaration we found is invalid, skip it.
2712 if (D->isInvalidDecl()) {
2713 F.erase();
2714 continue;
2715 }
2716
Richard Smith36f5cfe2012-03-09 08:00:36 +00002717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2718 if (FD->getNumParams() == 1 &&
2719 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2720 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002721 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002722 IsExactMatch = true;
2723 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2724 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2725 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2726 IsExactMatch = false;
2727 break;
2728 }
2729 }
2730 }
2731 }
2732
2733 if (IsExactMatch) {
2734 FoundExactMatch = true;
2735 AllowRawAndTemplate = false;
2736 if (FoundRaw || FoundTemplate) {
2737 // Go through again and remove the raw and template decls we've
2738 // already found.
2739 F.restart();
2740 FoundRaw = FoundTemplate = false;
2741 }
2742 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2743 FoundTemplate |= IsTemplate;
2744 FoundRaw |= IsRaw;
2745 } else {
2746 F.erase();
2747 }
2748 }
2749
2750 F.done();
2751
2752 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2753 // parameter type, that is used in preference to a raw literal operator
2754 // or literal operator template.
2755 if (FoundExactMatch)
2756 return LOLR_Cooked;
2757
2758 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2759 // operator template, but not both.
2760 if (FoundRaw && FoundTemplate) {
2761 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2762 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2763 Decl *D = *I;
2764 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2765 D = USD->getTargetDecl();
2766 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2767 D = FunTmpl->getTemplatedDecl();
2768 NoteOverloadCandidate(cast<FunctionDecl>(D));
2769 }
2770 return LOLR_Error;
2771 }
2772
2773 if (FoundRaw)
2774 return LOLR_Raw;
2775
2776 if (FoundTemplate)
2777 return LOLR_Template;
2778
2779 // Didn't find anything we could use.
2780 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2781 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2782 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2783 return LOLR_Error;
2784}
2785
John McCall7edb5fd2010-01-26 07:16:45 +00002786void ADLResult::insert(NamedDecl *New) {
2787 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2788
2789 // If we haven't yet seen a decl for this key, or the last decl
2790 // was exactly this one, we're done.
2791 if (Old == 0 || Old == New) {
2792 Old = New;
2793 return;
2794 }
2795
2796 // Otherwise, decide which is a more recent redeclaration.
2797 FunctionDecl *OldFD, *NewFD;
2798 if (isa<FunctionTemplateDecl>(New)) {
2799 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2800 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2801 } else {
2802 OldFD = cast<FunctionDecl>(Old);
2803 NewFD = cast<FunctionDecl>(New);
2804 }
2805
2806 FunctionDecl *Cursor = NewFD;
2807 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002808 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002809
2810 // If we got to the end without finding OldFD, OldFD is the newer
2811 // declaration; leave things as they are.
2812 if (!Cursor) return;
2813
2814 // If we do find OldFD, then NewFD is newer.
2815 if (Cursor == OldFD) break;
2816
2817 // Otherwise, keep looking.
2818 }
2819
2820 Old = New;
2821}
2822
Sebastian Redl644be852009-10-23 19:23:15 +00002823void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm834c0582013-08-09 18:02:13 +00002824 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002825 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002826 // Find all of the associated namespaces and classes based on the
2827 // arguments we have.
2828 AssociatedNamespaceSet AssociatedNamespaces;
2829 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002830 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002831 AssociatedNamespaces,
2832 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002833
Sebastian Redl644be852009-10-23 19:23:15 +00002834 QualType T1, T2;
2835 if (Operator) {
2836 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002837 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002838 T2 = Args[1]->getType();
2839 }
2840
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002841 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002842 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2843 // and let Y be the lookup set produced by argument dependent
2844 // lookup (defined as follows). If X contains [...] then Y is
2845 // empty. Otherwise Y is the set of declarations found in the
2846 // namespaces associated with the argument types as described
2847 // below. The set of declarations found by the lookup of the name
2848 // is the union of X and Y.
2849 //
2850 // Here, we compute Y and add its members to the overloaded
2851 // candidate set.
2852 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002853 NSEnd = AssociatedNamespaces.end();
2854 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002855 // When considering an associated namespace, the lookup is the
2856 // same as the lookup performed when the associated namespace is
2857 // used as a qualifier (3.4.3.2) except that:
2858 //
2859 // -- Any using-directives in the associated namespace are
2860 // ignored.
2861 //
John McCall6ff07852009-08-07 22:18:02 +00002862 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002863 // associated classes are visible within their respective
2864 // namespaces even if they are not visible during an ordinary
2865 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002866 DeclContext::lookup_result R = (*NS)->lookup(Name);
2867 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2868 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002869 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002870 // If the only declaration here is an ordinary friend, consider
2871 // it only if it was declared in an associated classes.
2872 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
Richard Smith22050f22013-07-17 23:53:16 +00002873 bool DeclaredInAssociatedClass = false;
2874 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2875 DeclContext *LexDC = DI->getLexicalDeclContext();
2876 if (isa<CXXRecordDecl>(LexDC) &&
2877 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2878 DeclaredInAssociatedClass = true;
2879 break;
2880 }
2881 }
2882 if (!DeclaredInAssociatedClass)
John McCall3f9a8a62009-08-11 06:59:38 +00002883 continue;
2884 }
Mike Stump1eb44332009-09-09 15:08:12 +00002885
John McCalla113e722010-01-26 06:04:06 +00002886 if (isa<UsingShadowDecl>(D))
2887 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002888
John McCalla113e722010-01-26 06:04:06 +00002889 if (isa<FunctionDecl>(D)) {
2890 if (Operator &&
2891 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2892 T1, T2, Context))
2893 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002894 } else if (!isa<FunctionTemplateDecl>(D))
2895 continue;
2896
2897 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002898 }
2899 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002900}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002901
2902//----------------------------------------------------------------------------
2903// Search for all visible declarations.
2904//----------------------------------------------------------------------------
2905VisibleDeclConsumer::~VisibleDeclConsumer() { }
2906
Richard Smithd67679d2013-08-20 20:35:18 +00002907bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2908
Douglas Gregor546be3c2009-12-30 17:04:44 +00002909namespace {
2910
2911class ShadowContextRAII;
2912
2913class VisibleDeclsRecord {
2914public:
2915 /// \brief An entry in the shadow map, which is optimized to store a
2916 /// single declaration (the common case) but can also store a list
2917 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002918 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002919
2920private:
2921 /// \brief A mapping from declaration names to the declarations that have
2922 /// this name within a particular scope.
2923 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2924
2925 /// \brief A list of shadow maps, which is used to model name hiding.
2926 std::list<ShadowMap> ShadowMaps;
2927
2928 /// \brief The declaration contexts we have already visited.
2929 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2930
2931 friend class ShadowContextRAII;
2932
2933public:
2934 /// \brief Determine whether we have already visited this context
2935 /// (and, if not, note that we are going to visit that context now).
2936 bool visitedContext(DeclContext *Ctx) {
2937 return !VisitedContexts.insert(Ctx);
2938 }
2939
Douglas Gregor8071e422010-08-15 06:18:01 +00002940 bool alreadyVisitedContext(DeclContext *Ctx) {
2941 return VisitedContexts.count(Ctx);
2942 }
2943
Douglas Gregor546be3c2009-12-30 17:04:44 +00002944 /// \brief Determine whether the given declaration is hidden in the
2945 /// current scope.
2946 ///
2947 /// \returns the declaration that hides the given declaration, or
2948 /// NULL if no such declaration exists.
2949 NamedDecl *checkHidden(NamedDecl *ND);
2950
2951 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002952 void add(NamedDecl *ND) {
2953 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2954 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002955};
2956
2957/// \brief RAII object that records when we've entered a shadow context.
2958class ShadowContextRAII {
2959 VisibleDeclsRecord &Visible;
2960
2961 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2962
2963public:
2964 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2965 Visible.ShadowMaps.push_back(ShadowMap());
2966 }
2967
2968 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002969 Visible.ShadowMaps.pop_back();
2970 }
2971};
2972
2973} // end anonymous namespace
2974
Douglas Gregor546be3c2009-12-30 17:04:44 +00002975NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002976 // Look through using declarations.
2977 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002978
Douglas Gregor546be3c2009-12-30 17:04:44 +00002979 unsigned IDNS = ND->getIdentifierNamespace();
2980 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2981 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2982 SM != SMEnd; ++SM) {
2983 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2984 if (Pos == SM->end())
2985 continue;
2986
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002987 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002988 IEnd = Pos->second.end();
2989 I != IEnd; ++I) {
2990 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002991 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002992 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002993 Decl::IDNS_ObjCProtocol)))
2994 continue;
2995
2996 // Protocols are in distinct namespaces from everything else.
2997 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2998 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2999 (*I)->getIdentifierNamespace() != IDNS)
3000 continue;
3001
Douglas Gregor0cc84042010-01-14 15:47:35 +00003002 // Functions and function templates in the same scope overload
3003 // rather than hide. FIXME: Look for hiding based on function
3004 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00003005 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00003006 ND->isFunctionOrFunctionTemplate() &&
3007 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00003008 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003009
Douglas Gregor546be3c2009-12-30 17:04:44 +00003010 // We've found a declaration that hides this one.
3011 return *I;
3012 }
3013 }
3014
3015 return 0;
3016}
3017
3018static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3019 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003020 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00003021 VisibleDeclConsumer &Consumer,
3022 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00003023 if (!Ctx)
3024 return;
3025
Douglas Gregor546be3c2009-12-30 17:04:44 +00003026 // Make sure we don't visit the same context twice.
3027 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3028 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003029
Douglas Gregor4923aa22010-07-02 20:37:36 +00003030 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3031 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3032
Douglas Gregor546be3c2009-12-30 17:04:44 +00003033 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00003034 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
3035 LEnd = Ctx->lookups_end();
3036 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003037 DeclContext::lookup_result R = *L;
3038 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3039 ++I) {
3040 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00003041 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003042 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003043 Visited.add(ND);
3044 }
Douglas Gregor70c23352010-12-09 21:44:02 +00003045 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003046 }
3047 }
3048
3049 // Traverse using directives for qualified name lookup.
3050 if (QualifiedNameLookup) {
3051 ShadowContextRAII Shadow(Visited);
3052 DeclContext::udir_iterator I, E;
3053 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003054 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003055 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003056 }
3057 }
3058
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003059 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003060 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00003061 if (!Record->hasDefinition())
3062 return;
3063
Douglas Gregor546be3c2009-12-30 17:04:44 +00003064 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
3065 BEnd = Record->bases_end();
3066 B != BEnd; ++B) {
3067 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003068
Douglas Gregor546be3c2009-12-30 17:04:44 +00003069 // Don't look into dependent bases, because name lookup can't look
3070 // there anyway.
3071 if (BaseType->isDependentType())
3072 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003073
Douglas Gregor546be3c2009-12-30 17:04:44 +00003074 const RecordType *Record = BaseType->getAs<RecordType>();
3075 if (!Record)
3076 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003077
Douglas Gregor546be3c2009-12-30 17:04:44 +00003078 // FIXME: It would be nice to be able to determine whether referencing
3079 // a particular member would be ambiguous. For example, given
3080 //
3081 // struct A { int member; };
3082 // struct B { int member; };
3083 // struct C : A, B { };
3084 //
3085 // void f(C *c) { c->### }
3086 //
3087 // accessing 'member' would result in an ambiguity. However, we
3088 // could be smart enough to qualify the member with the base
3089 // class, e.g.,
3090 //
3091 // c->B::member
3092 //
3093 // or
3094 //
3095 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003096
Douglas Gregor546be3c2009-12-30 17:04:44 +00003097 // Find results in this base class (and its bases).
3098 ShadowContextRAII Shadow(Visited);
3099 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003100 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003101 }
3102 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003103
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003104 // Traverse the contexts of Objective-C classes.
3105 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3106 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00003107 for (ObjCInterfaceDecl::visible_categories_iterator
3108 Cat = IFace->visible_categories_begin(),
3109 CatEnd = IFace->visible_categories_end();
3110 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003111 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00003112 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003113 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003114 }
3115
3116 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003117 for (ObjCInterfaceDecl::all_protocol_iterator
3118 I = IFace->all_referenced_protocol_begin(),
3119 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003120 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003122 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003123 }
3124
3125 // Traverse the superclass.
3126 if (IFace->getSuperClass()) {
3127 ShadowContextRAII Shadow(Visited);
3128 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003129 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003130 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003131
Douglas Gregorc220a182010-04-19 18:02:19 +00003132 // If there is an implementation, traverse it. We do this to find
3133 // synthesized ivars.
3134 if (IFace->getImplementation()) {
3135 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003136 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00003137 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00003138 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003139 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3140 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3141 E = Protocol->protocol_end(); I != E; ++I) {
3142 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003143 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003144 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003145 }
3146 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3147 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3148 E = Category->protocol_end(); I != E; ++I) {
3149 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003150 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003151 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003152 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003153
Douglas Gregorc220a182010-04-19 18:02:19 +00003154 // If there is an implementation, traverse it.
3155 if (Category->getImplementation()) {
3156 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003157 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00003158 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003160 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003161}
3162
3163static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3164 UnqualUsingDirectiveSet &UDirs,
3165 VisibleDeclConsumer &Consumer,
3166 VisibleDeclsRecord &Visited) {
3167 if (!S)
3168 return;
3169
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003170 if (!S->getEntity() ||
3171 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00003172 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00003173 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3174 // Walk through the declarations in this Scope.
3175 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3176 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003177 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003178 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003179 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003180 Visited.add(ND);
3181 }
3182 }
3183 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003184
Douglas Gregor711be1e2010-03-15 14:33:29 +00003185 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003186 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003187 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003188 // Look into this scope's declaration context, along with any of its
3189 // parent lookup contexts (e.g., enclosing classes), up to the point
3190 // where we hit the context stored in the next outer scope.
3191 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003192 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003193
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003194 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003195 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003196 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3197 if (Method->isInstanceMethod()) {
3198 // For instance methods, look for ivars in the method's interface.
3199 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3200 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003201 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithd67679d2013-08-20 20:35:18 +00003203 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003204 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003205 }
3206
3207 // We've already performed all of the name lookup that we need
3208 // to for Objective-C methods; the next context will be the
3209 // outer scope.
3210 break;
3211 }
3212
Douglas Gregor546be3c2009-12-30 17:04:44 +00003213 if (Ctx->isFunctionOrMethod())
3214 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215
3216 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003217 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003218 }
3219 } else if (!S->getParent()) {
3220 // Look into the translation unit scope. We walk through the translation
3221 // unit's declaration context, because the Scope itself won't have all of
3222 // the declarations if we loaded a precompiled header.
3223 // FIXME: We would like the translation unit's Scope object to point to the
3224 // translation unit, so we don't need this special "if" branch. However,
3225 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003226 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003227 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003228 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003229 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003230 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003231 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003232 }
3233
Douglas Gregor546be3c2009-12-30 17:04:44 +00003234 if (Entity) {
3235 // Lookup visible declarations in any namespaces found by using
3236 // directives.
3237 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3238 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3239 for (; UI != UEnd; ++UI)
3240 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003242 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003243 }
3244
3245 // Lookup names in the parent scope.
3246 ShadowContextRAII Shadow(Visited);
3247 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3248}
3249
3250void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003251 VisibleDeclConsumer &Consumer,
3252 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003253 // Determine the set of using directives available during
3254 // unqualified name lookup.
3255 Scope *Initial = S;
3256 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003257 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003258 // Find the first namespace or translation-unit scope.
3259 while (S && !isNamespaceOrTranslationUnitScope(S))
3260 S = S->getParent();
3261
3262 UDirs.visitScopeChain(Initial, S);
3263 }
3264 UDirs.done();
3265
3266 // Look for visible declarations.
3267 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003268 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003269 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003270 if (!IncludeGlobalScope)
3271 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003272 ShadowContextRAII Shadow(Visited);
3273 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3274}
3275
3276void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003277 VisibleDeclConsumer &Consumer,
3278 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003279 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003280 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003281 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003282 if (!IncludeGlobalScope)
3283 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003284 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003285 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003286 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003287}
3288
Chris Lattner4ae493c2011-02-18 02:08:43 +00003289/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003290/// If GnuLabelLoc is a valid source location, then this is a definition
3291/// of an __label__ label name, otherwise it is a normal label definition
3292/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003293LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003294 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003295 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003296 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003297
3298 if (GnuLabelLoc.isValid()) {
3299 // Local label definitions always shadow existing labels.
3300 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3301 Scope *S = CurScope;
3302 PushOnScopeChains(Res, S, true);
3303 return cast<LabelDecl>(Res);
3304 }
3305
3306 // Not a GNU local label.
3307 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3308 // If we found a label, check to see if it is in the same context as us.
3309 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003310 if (Res && Res->getDeclContext() != CurContext)
3311 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003312 if (Res == 0) {
3313 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003314 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3315 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003316 assert(S && "Not in a function?");
3317 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003318 }
Chris Lattner337e5502011-02-18 01:27:55 +00003319 return cast<LabelDecl>(Res);
3320}
3321
3322//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003323// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003324//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003325
3326namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003327
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003328typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003329typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003330typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003331
3332static const unsigned MaxTypoDistanceResultSets = 5;
3333
Douglas Gregor546be3c2009-12-30 17:04:44 +00003334class TypoCorrectionConsumer : public VisibleDeclConsumer {
3335 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003336 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003337
3338 /// \brief The results found that have the smallest edit distance
3339 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003340 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003341 /// The pointer value being set to the current DeclContext indicates
3342 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003343 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003344
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003345 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003346
Douglas Gregor546be3c2009-12-30 17:04:44 +00003347public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003348 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003349 : Typo(Typo->getName()),
Richard Smithd67679d2013-08-20 20:35:18 +00003350 SemaRef(SemaRef) {}
3351
3352 bool includeHiddenDecls() const { return true; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003353
Erik Verbruggend1205962011-10-06 07:27:49 +00003354 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3355 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003356 void FoundName(StringRef Name);
3357 void addKeywordResult(StringRef Keyword);
3358 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003359 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003360 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003361
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003362 typedef TypoResultsMap::iterator result_iterator;
3363 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003364 distance_iterator begin() { return CorrectionResults.begin(); }
3365 distance_iterator end() { return CorrectionResults.end(); }
3366 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3367 unsigned size() const { return CorrectionResults.size(); }
3368 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003369
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003370 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003371 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003372 }
3373
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003374 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003375 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003376 return (std::numeric_limits<unsigned>::max)();
3377
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003378 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003379 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003380 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003381
3382 TypoResultsMap &getBestResults() {
3383 return CorrectionResults.begin()->second;
3384 }
3385
Douglas Gregor546be3c2009-12-30 17:04:44 +00003386};
3387
3388}
3389
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003390void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003391 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003392 // Don't consider hidden names for typo correction.
3393 if (Hiding)
3394 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003395
Douglas Gregor546be3c2009-12-30 17:04:44 +00003396 // Only consider entities with identifiers for names, ignoring
3397 // special names (constructors, overloaded operators, selectors,
3398 // etc.).
3399 IdentifierInfo *Name = ND->getIdentifier();
3400 if (!Name)
3401 return;
3402
Richard Smithd67679d2013-08-20 20:35:18 +00003403 // Only consider visible declarations and declarations from modules with
3404 // names that exactly match.
3405 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3406 !findAcceptableDecl(SemaRef, ND))
3407 return;
3408
Douglas Gregor95f42922010-10-14 22:11:03 +00003409 FoundName(Name->getName());
3410}
3411
Chris Lattner5f9e2722011-07-23 10:55:15 +00003412void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003413 // Use a simple length-based heuristic to determine the minimum possible
3414 // edit distance. If the minimum isn't good enough, bail out early.
3415 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003416 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003417 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003418
Douglas Gregora1194772010-10-19 22:14:33 +00003419 // Compute an upper bound on the allowable edit distance, so that the
3420 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003421 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003422
Douglas Gregor546be3c2009-12-30 17:04:44 +00003423 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003424 // entity, and add the identifier to the list of results.
3425 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003426}
3427
Chris Lattner5f9e2722011-07-23 10:55:15 +00003428void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003429 // Compute the edit distance between the typo and this keyword,
3430 // and add the keyword to the list of results.
3431 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003432}
3433
Chris Lattner5f9e2722011-07-23 10:55:15 +00003434void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003435 NamedDecl *ND,
3436 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003437 NestedNameSpecifier *NNS,
3438 bool isKeyword) {
3439 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3440 if (isKeyword) TC.makeKeyword();
3441 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003442}
3443
3444void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003445 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003446 TypoResultList &CList =
3447 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003448
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003449 if (!CList.empty() && !CList.back().isResolved())
3450 CList.pop_back();
3451 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3452 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3453 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3454 RI != RIEnd; ++RI) {
3455 // If the Correction refers to a decl already in the result list,
3456 // replace the existing result if the string representation of Correction
3457 // comes before the current result alphabetically, then stop as there is
3458 // nothing more to be done to add Correction to the candidate set.
3459 if (RI->getCorrectionDecl() == NewND) {
3460 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3461 *RI = Correction;
3462 return;
3463 }
3464 }
3465 }
3466 if (CList.empty() || Correction.isResolved())
3467 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003468
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003469 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3470 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003471}
3472
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003473// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3474// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3475// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3476static void getNestedNameSpecifierIdentifiers(
3477 NestedNameSpecifier *NNS,
3478 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3479 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3480 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3481 else
3482 Identifiers.clear();
3483
3484 const IdentifierInfo *II = NULL;
3485
3486 switch (NNS->getKind()) {
3487 case NestedNameSpecifier::Identifier:
3488 II = NNS->getAsIdentifier();
3489 break;
3490
3491 case NestedNameSpecifier::Namespace:
3492 if (NNS->getAsNamespace()->isAnonymousNamespace())
3493 return;
3494 II = NNS->getAsNamespace()->getIdentifier();
3495 break;
3496
3497 case NestedNameSpecifier::NamespaceAlias:
3498 II = NNS->getAsNamespaceAlias()->getIdentifier();
3499 break;
3500
3501 case NestedNameSpecifier::TypeSpecWithTemplate:
3502 case NestedNameSpecifier::TypeSpec:
3503 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3504 break;
3505
3506 case NestedNameSpecifier::Global:
3507 return;
3508 }
3509
3510 if (II)
3511 Identifiers.push_back(II);
3512}
3513
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003514namespace {
3515
3516class SpecifierInfo {
3517 public:
3518 DeclContext* DeclCtx;
3519 NestedNameSpecifier* NameSpecifier;
3520 unsigned EditDistance;
3521
3522 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3523 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3524};
3525
Chris Lattner5f9e2722011-07-23 10:55:15 +00003526typedef SmallVector<DeclContext*, 4> DeclContextList;
3527typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003528
3529class NamespaceSpecifierSet {
3530 ASTContext &Context;
3531 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003532 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3533 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003534 bool isSorted;
3535
3536 SpecifierInfoList Specifiers;
3537 llvm::SmallSetVector<unsigned, 4> Distances;
3538 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3539
3540 /// \brief Helper for building the list of DeclContexts between the current
3541 /// context and the top of the translation unit
3542 static DeclContextList BuildContextChain(DeclContext *Start);
3543
3544 void SortNamespaces();
3545
3546 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003547 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3548 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003549 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003550 isSorted(false) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003551 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3552 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3553 CurNameSpecifierIdentifiers);
3554 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003555 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003556 // context.
3557 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3558 CEnd = CurContextChain.rend();
3559 C != CEnd; ++C) {
3560 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3561 CurContextIdentifiers.push_back(ND->getIdentifier());
3562 }
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003563
3564 // Add the global context as a NestedNameSpecifier
3565 Distances.insert(1);
3566 DistanceMap[1].push_back(
3567 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3568 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003569 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003570
3571 /// \brief Add the namespace to the set, computing the corresponding
3572 /// NestedNameSpecifier and its distance in the process.
3573 void AddNamespace(NamespaceDecl *ND);
3574
3575 typedef SpecifierInfoList::iterator iterator;
3576 iterator begin() {
3577 if (!isSorted) SortNamespaces();
3578 return Specifiers.begin();
3579 }
3580 iterator end() { return Specifiers.end(); }
3581};
3582
3583}
3584
3585DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0db9d202013-04-08 21:55:21 +00003586 assert(Start && "Building a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003587 DeclContextList Chain;
3588 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3589 DC = DC->getLookupParent()) {
3590 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3591 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3592 !(ND && ND->isAnonymousNamespace()))
3593 Chain.push_back(DC->getPrimaryContext());
3594 }
3595 return Chain;
3596}
3597
3598void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003599 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003600 sortedDistances.append(Distances.begin(), Distances.end());
3601
3602 if (sortedDistances.size() > 1)
3603 std::sort(sortedDistances.begin(), sortedDistances.end());
3604
3605 Specifiers.clear();
Craig Topper09d19ef2013-07-04 03:08:24 +00003606 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3607 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003608 DI != DIEnd; ++DI) {
3609 SpecifierInfoList &SpecList = DistanceMap[*DI];
3610 Specifiers.append(SpecList.begin(), SpecList.end());
3611 }
3612
3613 isSorted = true;
3614}
3615
3616void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003617 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003618 NestedNameSpecifier *NNS = NULL;
3619 unsigned NumSpecifiers = 0;
3620 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003621 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003622
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003623 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003624 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3625 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003626 C != CEnd && !NamespaceDeclChain.empty() &&
3627 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003628 NamespaceDeclChain.pop_back();
3629 }
3630
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003631 // Add an explicit leading '::' specifier if needed.
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00003632 if (NamespaceDeclChain.empty()) {
3633 NamespaceDeclChain = FullNamespaceDeclChain;
3634 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3635 } else if (NamespaceDecl *ND =
3636 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003637 IdentifierInfo *Name = ND->getIdentifier();
3638 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3639 Name) != CurContextIdentifiers.end() ||
3640 std::find(CurNameSpecifierIdentifiers.begin(),
3641 CurNameSpecifierIdentifiers.end(),
3642 Name) != CurNameSpecifierIdentifiers.end()) {
3643 NamespaceDeclChain = FullNamespaceDeclChain;
3644 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3645 }
3646 }
3647
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003648 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3649 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3650 CEnd = NamespaceDeclChain.rend();
3651 C != CEnd; ++C) {
3652 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3653 if (ND) {
3654 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3655 ++NumSpecifiers;
3656 }
3657 }
3658
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003659 // If the built NestedNameSpecifier would be replacing an existing
3660 // NestedNameSpecifier, use the number of component identifiers that
3661 // would need to be changed as the edit distance instead of the number
3662 // of components in the built NestedNameSpecifier.
3663 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3664 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3665 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3666 NumSpecifiers = llvm::ComputeEditDistance(
Robert Wilhelm834c0582013-08-09 18:02:13 +00003667 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3668 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003669 }
3670
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003671 isSorted = false;
3672 Distances.insert(NumSpecifiers);
3673 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003674}
3675
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003676/// \brief Perform name lookup for a possible result for typo correction.
3677static void LookupPotentialTypoResult(Sema &SemaRef,
3678 LookupResult &Res,
3679 IdentifierInfo *Name,
3680 Scope *S, CXXScopeSpec *SS,
3681 DeclContext *MemberContext,
3682 bool EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00003683 bool isObjCIvarLookup,
3684 bool FindHidden) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003685 Res.suppressDiagnostics();
3686 Res.clear();
3687 Res.setLookupName(Name);
Richard Smithd67679d2013-08-20 20:35:18 +00003688 Res.setAllowHidden(FindHidden);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003689 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003690 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003691 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003692 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3693 Res.addDecl(Ivar);
3694 Res.resolveKind();
3695 return;
3696 }
3697 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003698
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003699 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3700 Res.addDecl(Prop);
3701 Res.resolveKind();
3702 return;
3703 }
3704 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003705
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003706 SemaRef.LookupQualifiedName(Res, MemberContext);
3707 return;
3708 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709
3710 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003711 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003712
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003713 // Fake ivar lookup; this should really be part of
3714 // LookupParsedName.
3715 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3716 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003717 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003718 (Res.isSingleResult() &&
3719 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003720 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003721 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3722 Res.addDecl(IV);
3723 Res.resolveKind();
3724 }
3725 }
3726 }
3727}
3728
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003729/// \brief Add keywords to the consumer as possible typo corrections.
3730static void AddKeywordsToConsumer(Sema &SemaRef,
3731 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003732 Scope *S, CorrectionCandidateCallback &CCC,
3733 bool AfterNestedNameSpecifier) {
3734 if (AfterNestedNameSpecifier) {
3735 // For 'X::', we know exactly which keywords can appear next.
3736 Consumer.addKeywordResult("template");
3737 if (CCC.WantExpressionKeywords)
3738 Consumer.addKeywordResult("operator");
3739 return;
3740 }
3741
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003742 if (CCC.WantObjCSuper)
3743 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003744
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003745 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003746 // Add type-specifier keywords to the set of results.
Craig Topper3aa29df2013-07-15 08:24:27 +00003747 static const char *const CTypeSpecs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003748 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003749 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003750 "_Complex", "_Imaginary",
3751 // storage-specifiers as well
3752 "extern", "inline", "static", "typedef"
3753 };
3754
Craig Topperb9602322013-07-15 03:38:40 +00003755 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003756 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3757 Consumer.addKeywordResult(CTypeSpecs[I]);
3758
David Blaikie4e4d0842012-03-11 07:00:24 +00003759 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003760 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003761 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003762 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003763 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003764 Consumer.addKeywordResult("_Bool");
3765
David Blaikie4e4d0842012-03-11 07:00:24 +00003766 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003767 Consumer.addKeywordResult("class");
3768 Consumer.addKeywordResult("typename");
3769 Consumer.addKeywordResult("wchar_t");
3770
Richard Smith80ad52f2013-01-02 11:42:31 +00003771 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003772 Consumer.addKeywordResult("char16_t");
3773 Consumer.addKeywordResult("char32_t");
3774 Consumer.addKeywordResult("constexpr");
3775 Consumer.addKeywordResult("decltype");
3776 Consumer.addKeywordResult("thread_local");
3777 }
3778 }
3779
David Blaikie4e4d0842012-03-11 07:00:24 +00003780 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003781 Consumer.addKeywordResult("typeof");
3782 }
3783
David Blaikie4e4d0842012-03-11 07:00:24 +00003784 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003785 Consumer.addKeywordResult("const_cast");
3786 Consumer.addKeywordResult("dynamic_cast");
3787 Consumer.addKeywordResult("reinterpret_cast");
3788 Consumer.addKeywordResult("static_cast");
3789 }
3790
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003791 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003792 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003793 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003794 Consumer.addKeywordResult("false");
3795 Consumer.addKeywordResult("true");
3796 }
3797
David Blaikie4e4d0842012-03-11 07:00:24 +00003798 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topper3aa29df2013-07-15 08:24:27 +00003799 static const char *const CXXExprs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003800 "delete", "new", "operator", "throw", "typeid"
3801 };
Craig Topperb9602322013-07-15 03:38:40 +00003802 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003803 for (unsigned I = 0; I != NumCXXExprs; ++I)
3804 Consumer.addKeywordResult(CXXExprs[I]);
3805
3806 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3807 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3808 Consumer.addKeywordResult("this");
3809
Richard Smith80ad52f2013-01-02 11:42:31 +00003810 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003811 Consumer.addKeywordResult("alignof");
3812 Consumer.addKeywordResult("nullptr");
3813 }
3814 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003815
3816 if (SemaRef.getLangOpts().C11) {
3817 // FIXME: We should not suggest _Alignof if the alignof macro
3818 // is present.
3819 Consumer.addKeywordResult("_Alignof");
3820 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003821 }
3822
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003823 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003824 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3825 // Statements.
Craig Topper3aa29df2013-07-15 08:24:27 +00003826 static const char *const CStmts[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003827 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Topperb9602322013-07-15 03:38:40 +00003828 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003829 for (unsigned I = 0; I != NumCStmts; ++I)
3830 Consumer.addKeywordResult(CStmts[I]);
3831
David Blaikie4e4d0842012-03-11 07:00:24 +00003832 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003833 Consumer.addKeywordResult("catch");
3834 Consumer.addKeywordResult("try");
3835 }
3836
3837 if (S && S->getBreakParent())
3838 Consumer.addKeywordResult("break");
3839
3840 if (S && S->getContinueParent())
3841 Consumer.addKeywordResult("continue");
3842
3843 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3844 Consumer.addKeywordResult("case");
3845 Consumer.addKeywordResult("default");
3846 }
3847 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003848 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003849 Consumer.addKeywordResult("namespace");
3850 Consumer.addKeywordResult("template");
3851 }
3852
3853 if (S && S->isClassScope()) {
3854 Consumer.addKeywordResult("explicit");
3855 Consumer.addKeywordResult("friend");
3856 Consumer.addKeywordResult("mutable");
3857 Consumer.addKeywordResult("private");
3858 Consumer.addKeywordResult("protected");
3859 Consumer.addKeywordResult("public");
3860 Consumer.addKeywordResult("virtual");
3861 }
3862 }
3863
David Blaikie4e4d0842012-03-11 07:00:24 +00003864 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003865 Consumer.addKeywordResult("using");
3866
Richard Smith80ad52f2013-01-02 11:42:31 +00003867 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003868 Consumer.addKeywordResult("static_assert");
3869 }
3870 }
3871}
3872
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003873static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3874 TypoCorrection &Candidate) {
3875 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3876 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3877}
3878
Richard Smithd67679d2013-08-20 20:35:18 +00003879/// \brief Check whether the declarations found for a typo correction are
3880/// visible, and if none of them are, convert the correction to an 'import
3881/// a module' correction.
3882static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3883 DeclarationName TypoName) {
3884 if (TC.begin() == TC.end())
3885 return;
3886
3887 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3888
3889 for (/**/; DI != DE; ++DI)
3890 if (!LookupResult::isVisible(SemaRef, *DI))
3891 break;
3892 // Nothing to do if all decls are visible.
3893 if (DI == DE)
3894 return;
3895
3896 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3897 bool AnyVisibleDecls = !NewDecls.empty();
3898
3899 for (/**/; DI != DE; ++DI) {
3900 NamedDecl *VisibleDecl = *DI;
3901 if (!LookupResult::isVisible(SemaRef, *DI))
3902 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3903
3904 if (VisibleDecl) {
3905 if (!AnyVisibleDecls) {
3906 // Found a visible decl, discard all hidden ones.
3907 AnyVisibleDecls = true;
3908 NewDecls.clear();
3909 }
3910 NewDecls.push_back(VisibleDecl);
3911 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3912 NewDecls.push_back(*DI);
3913 }
3914
3915 if (NewDecls.empty())
3916 TC = TypoCorrection();
3917 else {
3918 TC.setCorrectionDecls(NewDecls);
3919 TC.setRequiresImport(!AnyVisibleDecls);
3920 }
3921}
3922
Douglas Gregor546be3c2009-12-30 17:04:44 +00003923/// \brief Try to "correct" a typo in the source code by finding
3924/// visible declarations whose names are similar to the name that was
3925/// present in the source code.
3926///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003927/// \param TypoName the \c DeclarationNameInfo structure that contains
3928/// the name that was present in the source code along with its location.
3929///
3930/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003931///
3932/// \param S the scope in which name lookup occurs.
3933///
3934/// \param SS the nested-name-specifier that precedes the name we're
3935/// looking for, if present.
3936///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003937/// \param CCC A CorrectionCandidateCallback object that provides further
3938/// validation of typo correction candidates. It also provides flags for
3939/// determining the set of keywords permitted.
3940///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003941/// \param MemberContext if non-NULL, the context in which to look for
3942/// a member access expression.
3943///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003945/// the nested-name-specifier SS.
3946///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003947/// \param OPT when non-NULL, the search for visible declarations will
3948/// also walk the protocols in the qualified interfaces of \p OPT.
3949///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003950/// \returns a \c TypoCorrection containing the corrected name if the typo
3951/// along with information such as the \c NamedDecl where the corrected name
3952/// was declared, and any additional \c NestedNameSpecifier needed to access
3953/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3954TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3955 Sema::LookupNameKind LookupKind,
3956 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003957 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003958 DeclContext *MemberContext,
3959 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003960 const ObjCObjectPointerType *OPT) {
Kaelyn Uhrain70571f42013-08-12 19:54:38 +00003961 // Always let the ExternalSource have the first chance at correction, even
3962 // if we would otherwise have given up.
3963 if (ExternalSource) {
3964 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
3965 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
3966 return Correction;
3967 }
3968
David Blaikie4e4d0842012-03-11 07:00:24 +00003969 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003970 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003971
Francois Pichet4d604d62011-12-03 15:55:29 +00003972 // In Microsoft mode, don't perform typo correction in a template member
3973 // function dependent context because it interferes with the "lookup into
3974 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003975 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003976 isa<CXXMethodDecl>(CurContext))
3977 return TypoCorrection();
3978
Douglas Gregor546be3c2009-12-30 17:04:44 +00003979 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003980 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003981 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003982 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003983
3984 // If the scope specifier itself was invalid, don't try to correct
3985 // typos.
3986 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003987 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003988
3989 // Never try to correct typos during template deduction or
3990 // instantiation.
3991 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003992 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003993
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003994 // Don't try to correct 'super'.
3995 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3996 return TypoCorrection();
3997
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003998 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003999
4000 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004001
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004002 // If a callback object considers an empty typo correction candidate to be
4003 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004004 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004005 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004006
Douglas Gregoraaf87162010-04-14 20:04:41 +00004007 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004008 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004009 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004010 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004011 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004012
4013 // Look in qualified interfaces.
4014 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004015 for (ObjCObjectPointerType::qual_iterator
4016 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004017 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004018 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004019 }
4020 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004021 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4022 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004023 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004024
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004025 // Provide a stop gap for files that are just seriously broken. Trying
4026 // to correct all typos can turn into a HUGE performance penalty, causing
4027 // some files to take minutes to get rejected by the parser.
4028 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004029 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004030 ++TyposCorrected;
4031
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004032 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00004033 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004034 IsUnqualifiedLookup = true;
4035 UnqualifiedTyposCorrectedMap::iterator Cached
4036 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004037 if (Cached != UnqualifiedTyposCorrected.end()) {
4038 // Add the cached value, unless it's a keyword or fails validation. In the
4039 // keyword case, we'll end up adding the keyword below.
4040 if (Cached->second) {
4041 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004042 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004043 Consumer.addCorrection(Cached->second);
4044 } else {
4045 // Only honor no-correction cache hits when a callback that will validate
4046 // correction candidates is not being used.
4047 if (!ValidatingCallback)
4048 return TypoCorrection();
4049 }
4050 }
4051 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004052 // Provide a stop gap for files that are just seriously broken. Trying
4053 // to correct all typos can turn into a HUGE performance penalty, causing
4054 // some files to take minutes to get rejected by the parser.
4055 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004056 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004057 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004058 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004059
Douglas Gregor01798682012-03-26 16:54:18 +00004060 // Determine whether we are going to search in the various namespaces for
4061 // corrections.
4062 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00004063 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00004064 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Richard Smithd67679d2013-08-20 20:35:18 +00004065 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004066 // adding or changing the nested name specifier.
4067 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00004068
4069 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004070 // For unqualified lookup, look through all of the names that we have
4071 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004072 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004073 for (IdentifierTable::iterator I = Context.Idents.begin(),
4074 IEnd = Context.Idents.end();
4075 I != IEnd; ++I)
4076 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004077
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004078 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004079 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004080 if (IdentifierInfoLookup *External
4081 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00004082 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004083 do {
4084 StringRef Name = Iter->Next();
4085 if (Name.empty())
4086 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00004087
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004088 Consumer.FoundName(Name);
4089 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00004090 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004091 }
4092
Richard Smith0f4b5be2012-06-08 21:35:42 +00004093 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004094
Douglas Gregoraaf87162010-04-14 20:04:41 +00004095 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004096 if (Consumer.empty()) {
4097 // If this was an unqualified lookup, note that no correction was found.
4098 if (IsUnqualifiedLookup)
4099 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004100
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004101 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004102 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004103
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004104 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4105 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004106 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004107 if (ED > 0 && Typo->getName().size() / ED < 3) {
4108 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00004109 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004110 (void)UnqualifiedTyposCorrected[Typo];
4111
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004112 return TypoCorrection();
4113 }
4114
Douglas Gregor01798682012-03-26 16:54:18 +00004115 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4116 // to search those namespaces.
4117 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004118 // Load any externally-known namespaces.
4119 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004120 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004121 LoadedExternalKnownNamespaces = true;
4122 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4123 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4124 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4125 }
4126
Nick Lewycky01a41142013-01-26 00:35:08 +00004127 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004128 KNI = KnownNamespaces.begin(),
4129 KNIEnd = KnownNamespaces.end();
4130 KNI != KNIEnd; ++KNI)
4131 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004132 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004133
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004134 // Weed out any names that could not be found by name lookup or, if a
4135 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004136 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004137 LookupResult TmpRes(*this, TypoName, LookupKind);
4138 TmpRes.suppressDiagnostics();
4139 while (!Consumer.empty()) {
4140 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
4141 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004142 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4143 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004144 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004145 // If we only want nested name specifier corrections, ignore potential
4146 // corrections that have a different base identifier from the typo.
4147 if (AllowOnlyNNSChanges &&
4148 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4149 TypoCorrectionConsumer::result_iterator Prev = I;
4150 ++I;
4151 DI->second.erase(Prev);
4152 continue;
4153 }
4154
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004155 // If the item already has been looked up or is a keyword, keep it.
4156 // If a validator callback object was given, drop the correction
4157 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004158 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00004159 for (TypoResultList::iterator RI = I->second.begin();
4160 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004161 TypoResultList::iterator Prev = RI;
4162 ++RI;
4163 if (Prev->isResolved()) {
4164 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00004165 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004166 else
4167 Viable = true;
4168 }
4169 }
4170 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004171 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004172 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004173 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004174 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004175 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00004176 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004177 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004178
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004179 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004180 TypoCorrection &Candidate = I->second.front();
4181 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004182 DeclContext *TempMemberContext = MemberContext;
4183 CXXScopeSpec *TempSS = SS;
4184retry_lookup:
4185 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4186 TempMemberContext, EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00004187 CCC.IsObjCIvarLookup,
4188 Name == TypoName.getName() &&
4189 !Candidate.WillReplaceSpecifier());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004190
4191 switch (TmpRes.getResultKind()) {
4192 case LookupResult::NotFound:
4193 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004194 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004195 if (TempSS) {
4196 // Immediately retry the lookup without the given CXXScopeSpec
4197 TempSS = NULL;
4198 Candidate.WillReplaceSpecifier(true);
4199 goto retry_lookup;
4200 }
4201 if (TempMemberContext) {
4202 if (SS && !TempSS)
4203 TempSS = SS;
4204 TempMemberContext = NULL;
4205 goto retry_lookup;
4206 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004207 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004208 // We didn't find this name in our scope, or didn't like what we found;
4209 // ignore it.
4210 {
4211 TypoCorrectionConsumer::result_iterator Next = I;
4212 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004213 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004214 I = Next;
4215 }
4216 break;
4217
4218 case LookupResult::Ambiguous:
4219 // We don't deal with ambiguities.
4220 return TypoCorrection();
4221
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004222 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004223 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004224 // Store all of the Decls for overloaded symbols
4225 for (LookupResult::iterator TRD = TmpRes.begin(),
4226 TRDEnd = TmpRes.end();
4227 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004228 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +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 }
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004234 break;
4235 }
4236
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004237 case LookupResult::Found: {
4238 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004239 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004240 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004241 if (!isCandidateViable(CCC, Candidate)) {
4242 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004243 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004244 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004245 break;
4246 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004247
4248 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004249 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004250
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004251 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004252 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00004253 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004254 // If there are results in the closest possible bucket, stop
4255 break;
4256
4257 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004258 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004259 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004260 for (SmallVector<TypoCorrection,
4261 16>::iterator QRI = QualifiedResults.begin(),
4262 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004263 QRI != QRIEnd; ++QRI) {
4264 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4265 NIEnd = Namespaces.end();
4266 NI != NIEnd; ++NI) {
4267 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004268
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004269 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004270 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004271 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004272
4273 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004274 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004275 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4276
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004277 // Any corrections added below will be validated in subsequent
4278 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004279 switch (TmpRes.getResultKind()) {
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004280 case LookupResult::Found:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004281 case LookupResult::FoundOverloaded: {
4282 TypoCorrection TC(*QRI);
4283 TC.setCorrectionSpecifier(NI->NameSpecifier);
4284 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004285 TC.setCallbackDistance(0); // Reset the callback distance
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004286 for (LookupResult::iterator TRD = TmpRes.begin(),
4287 TRDEnd = TmpRes.end();
4288 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004289 TC.addCorrectionDecl(*TRD);
4290 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004291 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004292 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004293 case LookupResult::NotFound:
4294 case LookupResult::NotFoundInCurrentInstantiation:
4295 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004296 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004297 break;
4298 }
4299 }
4300 }
4301 }
4302
4303 QualifiedResults.clear();
4304 }
4305
4306 // No corrections remain...
4307 if (Consumer.empty()) return TypoCorrection();
4308
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004309 TypoResultsMap &BestResults = Consumer.getBestResults();
4310 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004311
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004312 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004313 // If this was an unqualified lookup and we believe the callback
4314 // object wouldn't have filtered out possible corrections, note
4315 // that no correction was found.
4316 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004317 (void)UnqualifiedTyposCorrected[Typo];
4318
4319 return TypoCorrection();
4320 }
4321
Douglas Gregore24b5752010-10-14 20:34:08 +00004322 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004323 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004324 const TypoResultList &CorrectionList = BestResults.begin()->second;
4325 const TypoCorrection &Result = CorrectionList.front();
4326 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004327
Douglas Gregor53e4b552010-10-26 17:18:00 +00004328 // Don't correct to a keyword that's the same as the typo; the keyword
4329 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004330 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4331
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004332 // Record the correction for unqualified lookup.
4333 if (IsUnqualifiedLookup)
4334 UnqualifiedTyposCorrected[Typo] = Result;
4335
David Blaikie6952c012012-10-12 20:00:44 +00004336 TypoCorrection TC = Result;
4337 TC.setCorrectionRange(SS, TypoName);
Richard Smithd67679d2013-08-20 20:35:18 +00004338 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie6952c012012-10-12 20:00:44 +00004339 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004340 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004341 else if (BestResults.size() > 1
4342 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4343 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4344 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4345 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004346 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004347 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004348 // Prefer 'super' when we're completing in a message-receiver
4349 // context.
4350
4351 // Don't correct to a keyword that's the same as the typo; the keyword
4352 // wasn't actually in scope.
4353 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004354
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004355 // Record the correction for unqualified lookup.
4356 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004357 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004358
David Blaikie6952c012012-10-12 20:00:44 +00004359 TypoCorrection TC = BestResults["super"].front();
4360 TC.setCorrectionRange(SS, TypoName);
4361 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004363
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004364 // If this was an unqualified lookup and we believe the callback object did
4365 // not filter out possible corrections, note that no correction was found.
4366 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004367 (void)UnqualifiedTyposCorrected[Typo];
4368
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004369 return TypoCorrection();
4370}
4371
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004372void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4373 if (!CDecl) return;
4374
4375 if (isKeyword())
4376 CorrectionDecls.clear();
4377
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004378 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004379
4380 if (!CorrectionName)
4381 CorrectionName = CDecl->getDeclName();
4382}
4383
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004384std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4385 if (CorrectionNameSpec) {
4386 std::string tmpBuffer;
4387 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4388 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikie17828ca2013-05-14 21:04:00 +00004389 PrefixOStream << CorrectionName;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004390 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004391 }
4392
4393 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004394}
Kaelyn Uhrain20a7cf42013-04-03 16:59:49 +00004395
4396bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4397 if (!candidate.isResolved())
4398 return true;
4399
4400 if (candidate.isKeyword())
4401 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4402 WantRemainingKeywords || WantObjCSuper;
4403
4404 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4405 CDeclEnd = candidate.end();
4406 CDecl != CDeclEnd; ++CDecl) {
4407 if (!isa<TypeDecl>(*CDecl))
4408 return true;
4409 }
4410
4411 return WantTypeSpecifiers;
4412}
Kaelyn Uhrain761695f2013-07-08 23:13:39 +00004413
4414FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4415 bool HasExplicitTemplateArgs)
4416 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
4417 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4418 WantRemainingKeywords = false;
4419}
4420
4421bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4422 if (!candidate.getCorrectionDecl())
4423 return candidate.isKeyword();
4424
4425 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4426 DIEnd = candidate.end();
4427 DI != DIEnd; ++DI) {
4428 FunctionDecl *FD = 0;
4429 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4430 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4431 FD = FTD->getTemplatedDecl();
4432 if (!HasExplicitTemplateArgs && !FD) {
4433 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4434 // If the Decl is neither a function nor a template function,
4435 // determine if it is a pointer or reference to a function. If so,
4436 // check against the number of arguments expected for the pointee.
4437 QualType ValType = cast<ValueDecl>(ND)->getType();
4438 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4439 ValType = ValType->getPointeeType();
4440 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4441 if (FPT->getNumArgs() == NumArgs)
4442 return true;
4443 }
4444 }
4445 if (FD && FD->getNumParams() >= NumArgs &&
4446 FD->getMinRequiredArguments() <= NumArgs)
4447 return true;
4448 }
4449 return false;
4450}
Richard Smith2d670972013-08-17 00:46:16 +00004451
4452void Sema::diagnoseTypo(const TypoCorrection &Correction,
4453 const PartialDiagnostic &TypoDiag,
4454 bool ErrorRecovery) {
4455 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4456 ErrorRecovery);
4457}
4458
Richard Smithd67679d2013-08-20 20:35:18 +00004459/// Find which declaration we should import to provide the definition of
4460/// the given declaration.
4461static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4462 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4463 return VD->getDefinition();
4464 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4465 return FD->isDefined(FD) ? FD : 0;
4466 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4467 return TD->getDefinition();
4468 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4469 return ID->getDefinition();
4470 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4471 return PD->getDefinition();
4472 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4473 return getDefinitionToImport(TD->getTemplatedDecl());
4474 return 0;
4475}
4476
Richard Smith2d670972013-08-17 00:46:16 +00004477/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4478/// itself to allow external validation of the result, etc.
4479///
4480/// \param Correction The result of performing typo correction.
4481/// \param TypoDiag The diagnostic to produce. This will have the corrected
4482/// string added to it (and usually also a fixit).
4483/// \param PrevNote A note to use when indicating the location of the entity to
4484/// which we are correcting. Will have the correction string added to it.
4485/// \param ErrorRecovery If \c true (the default), the caller is going to
4486/// recover from the typo as if the corrected string had been typed.
4487/// In this case, \c PDiag must be an error, and we will attach a fixit
4488/// to it.
4489void Sema::diagnoseTypo(const TypoCorrection &Correction,
4490 const PartialDiagnostic &TypoDiag,
4491 const PartialDiagnostic &PrevNote,
4492 bool ErrorRecovery) {
4493 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4494 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4495 FixItHint FixTypo = FixItHint::CreateReplacement(
4496 Correction.getCorrectionRange(), CorrectedStr);
4497
Richard Smithd67679d2013-08-20 20:35:18 +00004498 // Maybe we're just missing a module import.
4499 if (Correction.requiresImport()) {
4500 NamedDecl *Decl = Correction.getCorrectionDecl();
4501 assert(Decl && "import required but no declaration to import");
4502
4503 // Suggest importing a module providing the definition of this entity, if
4504 // possible.
4505 const NamedDecl *Def = getDefinitionToImport(Decl);
4506 if (!Def)
4507 Def = Decl;
4508 Module *Owner = Def->getOwningModule();
4509 assert(Owner && "definition of hidden declaration is not in a module");
4510
4511 Diag(Correction.getCorrectionRange().getBegin(),
4512 diag::err_module_private_declaration)
4513 << Def << Owner->getFullModuleName();
4514 Diag(Def->getLocation(), diag::note_previous_declaration);
4515
4516 // Recover by implicitly importing this module.
4517 if (!isSFINAEContext() && ErrorRecovery)
4518 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4519 Owner);
4520 return;
4521 }
4522
Richard Smith2d670972013-08-17 00:46:16 +00004523 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4524 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4525
4526 NamedDecl *ChosenDecl =
4527 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4528 if (PrevNote.getDiagID() && ChosenDecl)
4529 Diag(ChosenDecl->getLocation(), PrevNote)
4530 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4531}