blob: adda1b947910e077cbe79aa3a3b169603b72c719 [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 Smithb7751002013-07-25 23:08:39 +00001232NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1233 assert(!isVisible(SemaRef, D) && "not in slow case");
1234
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 Smithb7751002013-07-25 23:08:39 +00001238 if (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
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001246/// @brief Perform unqualified name lookup starting from a given
1247/// scope.
1248///
1249/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1250/// used to find names within the current scope. For example, 'x' in
1251/// @code
1252/// int x;
1253/// int f() {
1254/// return x; // unqualified name look finds 'x' in the global scope
1255/// }
1256/// @endcode
1257///
1258/// Different lookup criteria can find different names. For example, a
1259/// particular scope can have both a struct and a function of the same
1260/// name, and each can be found by certain lookup criteria. For more
1261/// information about lookup criteria, see the documentation for the
1262/// class LookupCriteria.
1263///
1264/// @param S The scope from which unqualified name lookup will
1265/// begin. If the lookup criteria permits, name lookup may also search
1266/// in the parent scopes.
1267///
James Dennett8da16872012-06-22 10:32:46 +00001268/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1269/// look up and the lookup kind), and is updated with the results of lookup
1270/// including zero or more declarations and possibly additional information
1271/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001272///
James Dennett8da16872012-06-22 10:32:46 +00001273/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001274bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1275 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001276 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001277
John McCalla24dc2e2009-11-17 02:14:36 +00001278 LookupNameKind NameKind = R.getLookupKind();
1279
David Blaikie4e4d0842012-03-11 07:00:24 +00001280 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001281 // Unqualified name lookup in C/Objective-C is purely lexical, so
1282 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001283 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001284 // Find the nearest non-transparent declaration scope.
1285 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001286 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001287 static_cast<DeclContext *>(S->getEntity())
1288 ->isTransparentContext()))
1289 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001290 }
1291
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001292 // Scan up the scope chain looking for a decl that matches this
1293 // identifier that is in the appropriate namespace. This search
1294 // should not take long, as shadowing of names is uncommon, and
1295 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001296 bool LeftStartingScope = false;
1297
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001298 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001299 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001300 I != IEnd; ++I)
Richard Smithb7751002013-07-25 23:08:39 +00001301 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001302 if (NameKind == LookupRedeclarationWithLinkage) {
1303 // Determine whether this (or a previous) declaration is
1304 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001305 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001306 LeftStartingScope = true;
1307
1308 // If we found something outside of our starting scope that
1309 // does not have linkage, skip it.
Richard Smithdd9459f2013-08-13 18:18:50 +00001310 if (LeftStartingScope && !((*I)->hasLinkage())) {
1311 R.setShadowed();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001312 continue;
Richard Smithdd9459f2013-08-13 18:18:50 +00001313 }
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001314 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001315 else if (NameKind == LookupObjCImplicitSelfParam &&
1316 !isa<ImplicitParamDecl>(*I))
1317 continue;
Richard Smithb7751002013-07-25 23:08:39 +00001318
Douglas Gregor55368912011-12-14 16:03:29 +00001319 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001320
Douglas Gregor7a537402012-01-03 23:26:26 +00001321 // Check whether there are any other declarations with the same name
1322 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001323 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001324 // Find the scope in which this declaration was declared (if it
1325 // actually exists in a Scope).
1326 while (S && !S->isDeclScope(D))
1327 S = S->getParent();
1328
1329 // If the scope containing the declaration is the translation unit,
1330 // then we'll need to perform our checks based on the matching
1331 // DeclContexts rather than matching scopes.
1332 if (S && isNamespaceOrTranslationUnitScope(S))
1333 S = 0;
1334
1335 // Compute the DeclContext, if we need it.
1336 DeclContext *DC = 0;
1337 if (!S)
1338 DC = (*I)->getDeclContext()->getRedeclContext();
1339
Douglas Gregorda795b42012-01-04 16:44:10 +00001340 IdentifierResolver::iterator LastI = I;
1341 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001342 if (S) {
1343 // Match based on scope.
1344 if (!S->isDeclScope(*LastI))
1345 break;
1346 } else {
1347 // Match based on DeclContext.
1348 DeclContext *LastDC
1349 = (*LastI)->getDeclContext()->getRedeclContext();
1350 if (!LastDC->Equals(DC))
1351 break;
1352 }
Richard Smithb7751002013-07-25 23:08:39 +00001353
1354 // If the declaration is in the right namespace and visible, add it.
1355 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1356 R.addDecl(LastD);
Douglas Gregorda795b42012-01-04 16:44:10 +00001357 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001358
Douglas Gregorda795b42012-01-04 16:44:10 +00001359 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001360 }
John McCallf36e02d2009-10-09 21:13:30 +00001361 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001362 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001363 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001364 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001365 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001366 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001367 }
1368
1369 // If we didn't find a use of this identifier, and if the identifier
1370 // corresponds to a compiler builtin, create the decl object for the builtin
1371 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001372 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1373 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001374
Axel Naumannf8291a12011-02-24 16:47:47 +00001375 // If we didn't find a use of this identifier, the ExternalSource
1376 // may be able to handle the situation.
1377 // Note: some lookup failures are expected!
1378 // See e.g. R.isForRedeclaration().
1379 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001380}
1381
John McCall6e247262009-10-10 05:48:19 +00001382/// @brief Perform qualified name lookup in the namespaces nominated by
1383/// using directives by the given context.
1384///
1385/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001386/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001387/// (where X is the global namespace), let S be the set of all
1388/// declarations of m in X and in the transitive closure of all
1389/// namespaces nominated by using-directives in X and its used
1390/// namespaces, except that using-directives are ignored in any
1391/// namespace, including X, directly containing one or more
1392/// declarations of m. No namespace is searched more than once in
1393/// the lookup of a name. If S is the empty set, the program is
1394/// ill-formed. Otherwise, if S has exactly one member, or if the
1395/// context of the reference is a using-declaration
1396/// (namespace.udecl), S is the required set of declarations of
1397/// m. Otherwise if the use of m is not one that allows a unique
1398/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001399///
John McCall6e247262009-10-10 05:48:19 +00001400/// C++98 [namespace.qual]p5:
1401/// During the lookup of a qualified namespace member name, if the
1402/// lookup finds more than one declaration of the member, and if one
1403/// declaration introduces a class name or enumeration name and the
1404/// other declarations either introduce the same object, the same
1405/// enumerator or a set of functions, the non-type name hides the
1406/// class or enumeration name if and only if the declarations are
1407/// from the same namespace; otherwise (the declarations are from
1408/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001409static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001410 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001411 assert(StartDC->isFileContext() && "start context is not a file context");
1412
1413 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1414 DeclContext::udir_iterator E = StartDC->using_directives_end();
1415
1416 if (I == E) return false;
1417
1418 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001419 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001420 Visited.insert(StartDC);
1421
1422 // We have not yet looked into these namespaces, much less added
1423 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001424 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001425
1426 // We have already looked into the initial namespace; seed the queue
1427 // with its using-children.
1428 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001429 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001430 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001431 Queue.push_back(ND);
1432 }
1433
1434 // The easiest way to implement the restriction in [namespace.qual]p5
1435 // is to check whether any of the individual results found a tag
1436 // and, if so, to declare an ambiguity if the final result is not
1437 // a tag.
1438 bool FoundTag = false;
1439 bool FoundNonTag = false;
1440
John McCall7d384dd2009-11-18 07:57:50 +00001441 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001442
1443 bool Found = false;
1444 while (!Queue.empty()) {
1445 NamespaceDecl *ND = Queue.back();
1446 Queue.pop_back();
1447
1448 // We go through some convolutions here to avoid copying results
1449 // between LookupResults.
1450 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001451 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001452 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001453
1454 if (FoundDirect) {
1455 // First do any local hiding.
1456 DirectR.resolveKind();
1457
1458 // If the local result is a tag, remember that.
1459 if (DirectR.isSingleTagDecl())
1460 FoundTag = true;
1461 else
1462 FoundNonTag = true;
1463
1464 // Append the local results to the total results if necessary.
1465 if (UseLocal) {
1466 R.addAllDecls(LocalR);
1467 LocalR.clear();
1468 }
1469 }
1470
1471 // If we find names in this namespace, ignore its using directives.
1472 if (FoundDirect) {
1473 Found = true;
1474 continue;
1475 }
1476
1477 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1478 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001479 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001480 Queue.push_back(Nom);
1481 }
1482 }
1483
1484 if (Found) {
1485 if (FoundTag && FoundNonTag)
1486 R.setAmbiguousQualifiedTagHiding();
1487 else
1488 R.resolveKind();
1489 }
1490
1491 return Found;
1492}
1493
Douglas Gregor8071e422010-08-15 06:18:01 +00001494/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001495static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001496 CXXBasePath &Path,
1497 void *Name) {
1498 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001499
Douglas Gregor8071e422010-08-15 06:18:01 +00001500 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1501 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001502 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001503}
1504
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001505/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001506/// static members, nested types, and enumerators.
1507template<typename InputIterator>
1508static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1509 Decl *D = (*First)->getUnderlyingDecl();
1510 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1511 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001512
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001513 if (isa<CXXMethodDecl>(D)) {
1514 // Determine whether all of the methods are static.
1515 bool AllMethodsAreStatic = true;
1516 for(; First != Last; ++First) {
1517 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001518
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001519 if (!isa<CXXMethodDecl>(D)) {
1520 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1521 break;
1522 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001523
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001524 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1525 AllMethodsAreStatic = false;
1526 break;
1527 }
1528 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001529
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001530 if (AllMethodsAreStatic)
1531 return true;
1532 }
1533
1534 return false;
1535}
1536
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001537/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001538///
1539/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1540/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001541/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001542///
1543/// Different lookup criteria can find different names. For example, a
1544/// particular scope can have both a struct and a function of the same
1545/// name, and each can be found by certain lookup criteria. For more
1546/// information about lookup criteria, see the documentation for the
1547/// class LookupCriteria.
1548///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001549/// \param R captures both the lookup criteria and any lookup results found.
1550///
1551/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001552/// search. If the lookup criteria permits, name lookup may also search
1553/// in the parent contexts or (for C++ classes) base classes.
1554///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001555/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001556/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001557///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001558/// \returns true if lookup succeeded, false if it failed.
1559bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1560 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001561 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001562
John McCalla24dc2e2009-11-17 02:14:36 +00001563 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001564 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001566 // Make sure that the declaration context is complete.
1567 assert((!isa<TagDecl>(LookupCtx) ||
1568 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001569 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001570 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001571 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001573 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001574 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001575 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001576 if (isa<CXXRecordDecl>(LookupCtx))
1577 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001578 return true;
1579 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001580
John McCall6e247262009-10-10 05:48:19 +00001581 // Don't descend into implied contexts for redeclarations.
1582 // C++98 [namespace.qual]p6:
1583 // In a declaration for a namespace member in which the
1584 // declarator-id is a qualified-id, given that the qualified-id
1585 // for the namespace member has the form
1586 // nested-name-specifier unqualified-id
1587 // the unqualified-id shall name a member of the namespace
1588 // designated by the nested-name-specifier.
1589 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001590 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001591 return false;
1592
John McCalla24dc2e2009-11-17 02:14:36 +00001593 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001594 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001595 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001596
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001597 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001598 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001599 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001600 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001601 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001602
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001603 // If we're performing qualified name lookup into a dependent class,
1604 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001605 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001606 // template instantiation time (at which point all bases will be available)
1607 // or we have to fail.
1608 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1609 LookupRec->hasAnyDependentBases()) {
1610 R.setNotFoundInCurrentInstantiation();
1611 return false;
1612 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001613
Douglas Gregor7176fff2009-01-15 00:26:24 +00001614 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001615 CXXBasePaths Paths;
1616 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001617
1618 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001619 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001620 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001621 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001622 case LookupOrdinaryName:
1623 case LookupMemberName:
1624 case LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +00001625 case LookupLocalFriendName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001626 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1627 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001628
Douglas Gregora8f32e02009-10-06 17:59:45 +00001629 case LookupTagName:
1630 BaseCallback = &CXXRecordDecl::FindTagMember;
1631 break;
John McCall9f54ad42009-12-10 09:41:52 +00001632
Douglas Gregor8071e422010-08-15 06:18:01 +00001633 case LookupAnyName:
1634 BaseCallback = &LookupAnyMember;
1635 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001636
John McCall9f54ad42009-12-10 09:41:52 +00001637 case LookupUsingDeclName:
1638 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001639
Douglas Gregora8f32e02009-10-06 17:59:45 +00001640 case LookupOperatorName:
1641 case LookupNamespaceName:
1642 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001643 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001644 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001645 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001646
Douglas Gregora8f32e02009-10-06 17:59:45 +00001647 case LookupNestedNameSpecifierName:
1648 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1649 break;
1650 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001651
John McCalla24dc2e2009-11-17 02:14:36 +00001652 if (!LookupRec->lookupInBases(BaseCallback,
1653 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001654 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001655
John McCall92f88312010-01-23 00:46:32 +00001656 R.setNamingClass(LookupRec);
1657
Douglas Gregor7176fff2009-01-15 00:26:24 +00001658 // C++ [class.member.lookup]p2:
1659 // [...] If the resulting set of declarations are not all from
1660 // sub-objects of the same type, or the set has a nonstatic member
1661 // and includes members from distinct sub-objects, there is an
1662 // ambiguity and the program is ill-formed. Otherwise that set is
1663 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001664 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001665 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001666 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001667
Douglas Gregora8f32e02009-10-06 17:59:45 +00001668 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001669 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001670 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001671
John McCall46460a62010-01-20 21:53:11 +00001672 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1673 // across all paths.
1674 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001675
Douglas Gregor7176fff2009-01-15 00:26:24 +00001676 // Determine whether we're looking at a distinct sub-object or not.
1677 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001678 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001679 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1680 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001681 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001682 }
1683
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001684 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001685 != Context.getCanonicalType(PathElement.Base->getType())) {
1686 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001687 // different types. If the declaration sets aren't the same, this
1688 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001689 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001690 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001691 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1692 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001693
David Blaikie3bc93e32012-12-19 00:45:41 +00001694 while (FirstD != FirstPath->Decls.end() &&
1695 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001696 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1697 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1698 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001699
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001700 ++FirstD;
1701 ++CurrentD;
1702 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001703
David Blaikie3bc93e32012-12-19 00:45:41 +00001704 if (FirstD == FirstPath->Decls.end() &&
1705 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001706 continue;
1707 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001708
John McCallf36e02d2009-10-09 21:13:30 +00001709 R.setAmbiguousBaseSubobjectTypes(Paths);
1710 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001711 }
1712
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001713 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001714 // We have a different subobject of the same type.
1715
1716 // C++ [class.member.lookup]p5:
1717 // A static member, a nested type or an enumerator defined in
1718 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001719 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001720 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001721 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001722
Douglas Gregor7176fff2009-01-15 00:26:24 +00001723 // We have found a nonstatic member name in multiple, distinct
1724 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001725 R.setAmbiguousBaseSubobjects(Paths);
1726 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001727 }
1728 }
1729
1730 // Lookup in a base class succeeded; return these results.
1731
David Blaikie3bc93e32012-12-19 00:45:41 +00001732 DeclContext::lookup_result DR = Paths.front().Decls;
1733 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001734 NamedDecl *D = *I;
1735 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1736 D->getAccess());
1737 R.addDecl(D, AS);
1738 }
John McCallf36e02d2009-10-09 21:13:30 +00001739 R.resolveKind();
1740 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001741}
1742
1743/// @brief Performs name lookup for a name that was parsed in the
1744/// source code, and may contain a C++ scope specifier.
1745///
1746/// This routine is a convenience routine meant to be called from
1747/// contexts that receive a name and an optional C++ scope specifier
1748/// (e.g., "N::M::x"). It will then perform either qualified or
1749/// unqualified name lookup (with LookupQualifiedName or LookupName,
1750/// respectively) on the given name and return those results.
1751///
1752/// @param S The scope from which unqualified name lookup will
1753/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001754///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001755/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001756///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001757/// @param EnteringContext Indicates whether we are going to enter the
1758/// context of the scope-specifier SS (if present).
1759///
John McCallf36e02d2009-10-09 21:13:30 +00001760/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001761bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001762 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001763 if (SS && SS->isInvalid()) {
1764 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001765 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001766 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001767 }
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Douglas Gregor495c35d2009-08-25 22:51:20 +00001769 if (SS && SS->isSet()) {
1770 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001771 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001772 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001773 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001774 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001775
John McCalla24dc2e2009-11-17 02:14:36 +00001776 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001777 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001778 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001779
Douglas Gregor495c35d2009-08-25 22:51:20 +00001780 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001781 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001782 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001783 R.setNotFoundInCurrentInstantiation();
1784 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001785 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001786 }
1787
Mike Stump1eb44332009-09-09 15:08:12 +00001788 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001789 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001790}
1791
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001792
James Dennett16ae9de2012-06-22 10:16:05 +00001793/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001794/// from name lookup.
1795///
James Dennett16ae9de2012-06-22 10:16:05 +00001796/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump1eb44332009-09-09 15:08:12 +00001797///
James Dennett16ae9de2012-06-22 10:16:05 +00001798/// \returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001799bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001800 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1801
John McCalla24dc2e2009-11-17 02:14:36 +00001802 DeclarationName Name = Result.getLookupName();
1803 SourceLocation NameLoc = Result.getNameLoc();
1804 SourceRange LookupRange = Result.getContextRange();
1805
John McCall6e247262009-10-10 05:48:19 +00001806 switch (Result.getAmbiguityKind()) {
1807 case LookupResult::AmbiguousBaseSubobjects: {
1808 CXXBasePaths *Paths = Result.getBasePaths();
1809 QualType SubobjectType = Paths->front().back().Base->getType();
1810 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1811 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1812 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001813
David Blaikie3bc93e32012-12-19 00:45:41 +00001814 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001815 while (isa<CXXMethodDecl>(*Found) &&
1816 cast<CXXMethodDecl>(*Found)->isStatic())
1817 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001818
John McCall6e247262009-10-10 05:48:19 +00001819 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001820
John McCall6e247262009-10-10 05:48:19 +00001821 return true;
1822 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001823
John McCall6e247262009-10-10 05:48:19 +00001824 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001825 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1826 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001827
John McCall6e247262009-10-10 05:48:19 +00001828 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001829 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001830 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1831 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001832 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001833 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001834 if (DeclsPrinted.insert(D).second)
1835 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1836 }
1837
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001838 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001839 }
1840
John McCall6e247262009-10-10 05:48:19 +00001841 case LookupResult::AmbiguousTagHiding: {
1842 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001843
John McCall6e247262009-10-10 05:48:19 +00001844 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1845
1846 LookupResult::iterator DI, DE = Result.end();
1847 for (DI = Result.begin(); DI != DE; ++DI)
1848 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1849 TagDecls.insert(TD);
1850 Diag(TD->getLocation(), diag::note_hidden_tag);
1851 }
1852
1853 for (DI = Result.begin(); DI != DE; ++DI)
1854 if (!isa<TagDecl>(*DI))
1855 Diag((*DI)->getLocation(), diag::note_hiding_object);
1856
1857 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001858 LookupResult::Filter F = Result.makeFilter();
1859 while (F.hasNext()) {
1860 if (TagDecls.count(F.next()))
1861 F.erase();
1862 }
1863 F.done();
John McCall6e247262009-10-10 05:48:19 +00001864
1865 return true;
1866 }
1867
1868 case LookupResult::AmbiguousReference: {
1869 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001870
John McCall6e247262009-10-10 05:48:19 +00001871 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1872 for (; DI != DE; ++DI)
1873 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001874
John McCall6e247262009-10-10 05:48:19 +00001875 return true;
1876 }
1877 }
1878
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001879 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001880}
Douglas Gregorfa047642009-02-04 00:32:51 +00001881
John McCallc7e04da2010-05-28 18:45:08 +00001882namespace {
1883 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001884 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001885 Sema::AssociatedNamespaceSet &Namespaces,
1886 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001887 : S(S), Namespaces(Namespaces), Classes(Classes),
1888 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001889 }
1890
1891 Sema &S;
1892 Sema::AssociatedNamespaceSet &Namespaces;
1893 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001894 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001895 };
1896}
1897
Mike Stump1eb44332009-09-09 15:08:12 +00001898static void
John McCallc7e04da2010-05-28 18:45:08 +00001899addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001900
Douglas Gregor54022952010-04-30 07:08:38 +00001901static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1902 DeclContext *Ctx) {
1903 // Add the associated namespace for this class.
1904
1905 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1906 // be a locally scoped record.
1907
Sebastian Redl410c4f22010-08-31 20:53:31 +00001908 // We skip out of inline namespaces. The innermost non-inline namespace
1909 // contains all names of all its nested inline namespaces anyway, so we can
1910 // replace the entire inline namespace tree with its root.
1911 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1912 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001913 Ctx = Ctx->getParent();
1914
John McCall6ff07852009-08-07 22:18:02 +00001915 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001916 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001917}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001918
Mike Stump1eb44332009-09-09 15:08:12 +00001919// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001920// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001921static void
John McCallc7e04da2010-05-28 18:45:08 +00001922addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1923 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001924 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001925 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001926 switch (Arg.getKind()) {
1927 case TemplateArgument::Null:
1928 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Douglas Gregor69be8d62009-07-08 07:51:57 +00001930 case TemplateArgument::Type:
1931 // [...] the namespaces and classes associated with the types of the
1932 // template arguments provided for template type parameters (excluding
1933 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001934 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001935 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001936
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001937 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001938 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001939 // [...] the namespaces in which any template template arguments are
1940 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001941 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001942 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001943 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001944 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001945 DeclContext *Ctx = ClassTemplate->getDeclContext();
1946 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001947 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001948 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001949 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001950 }
1951 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001952 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001953
Douglas Gregor788cd062009-11-11 01:00:40 +00001954 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001955 case TemplateArgument::Integral:
1956 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001957 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001958 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001959 // associated namespaces. ]
1960 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Douglas Gregor69be8d62009-07-08 07:51:57 +00001962 case TemplateArgument::Pack:
1963 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1964 PEnd = Arg.pack_end();
1965 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001966 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001967 break;
1968 }
1969}
1970
Douglas Gregorfa047642009-02-04 00:32:51 +00001971// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001972// argument-dependent lookup with an argument of class type
1973// (C++ [basic.lookup.koenig]p2).
1974static void
John McCallc7e04da2010-05-28 18:45:08 +00001975addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1976 CXXRecordDecl *Class) {
1977
1978 // Just silently ignore anything whose name is __va_list_tag.
1979 if (Class->getDeclName() == Result.S.VAListTagName)
1980 return;
1981
Douglas Gregorfa047642009-02-04 00:32:51 +00001982 // C++ [basic.lookup.koenig]p2:
1983 // [...]
1984 // -- If T is a class type (including unions), its associated
1985 // classes are: the class itself; the class of which it is a
1986 // member, if any; and its direct and indirect base
1987 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001988 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001989
1990 // Add the class of which it is a member, if any.
1991 DeclContext *Ctx = Class->getDeclContext();
1992 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001993 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001994 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001995 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Douglas Gregorfa047642009-02-04 00:32:51 +00001997 // Add the class itself. If we've already seen this class, we don't
1998 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001999 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00002000 return;
2001
Mike Stump1eb44332009-09-09 15:08:12 +00002002 // -- If T is a template-id, its associated namespaces and classes are
2003 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002004 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00002005 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00002006 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00002007 // namespaces in which any template template arguments are defined; and
2008 // the classes in which any member templates used as template template
2009 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00002010 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00002011 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00002012 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2013 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2014 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002015 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002016 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002017 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Douglas Gregor69be8d62009-07-08 07:51:57 +00002019 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2020 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00002021 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002022 }
Mike Stump1eb44332009-09-09 15:08:12 +00002023
John McCall86ff3082010-02-04 22:26:26 +00002024 // Only recurse into base classes for complete types.
2025 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00002026 QualType type = Result.S.Context.getTypeDeclType(Class);
2027 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
2028 /*no diagnostic*/ 0))
2029 return;
John McCall86ff3082010-02-04 22:26:26 +00002030 }
2031
Douglas Gregorfa047642009-02-04 00:32:51 +00002032 // Add direct and indirect base classes along with their associated
2033 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002034 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00002035 Bases.push_back(Class);
2036 while (!Bases.empty()) {
2037 // Pop this class off the stack.
2038 Class = Bases.back();
2039 Bases.pop_back();
2040
2041 // Visit the base classes.
2042 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
2043 BaseEnd = Class->bases_end();
2044 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002045 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00002046 // In dependent contexts, we do ADL twice, and the first time around,
2047 // the base type might be a dependent TemplateSpecializationType, or a
2048 // TemplateTypeParmType. If that happens, simply ignore it.
2049 // FIXME: If we want to support export, we probably need to add the
2050 // namespace of the template in a TemplateSpecializationType, or even
2051 // the classes and namespaces of known non-dependent arguments.
2052 if (!BaseType)
2053 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002054 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002055 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002056 // Find the associated namespace for this base class.
2057 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00002058 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002059
2060 // Make sure we visit the bases of this base class.
2061 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2062 Bases.push_back(BaseDecl);
2063 }
2064 }
2065 }
2066}
2067
2068// \brief Add the associated classes and namespaces for
2069// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00002070// (C++ [basic.lookup.koenig]p2).
2071static void
John McCallc7e04da2010-05-28 18:45:08 +00002072addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002073 // C++ [basic.lookup.koenig]p2:
2074 //
2075 // For each argument type T in the function call, there is a set
2076 // of zero or more associated namespaces and a set of zero or more
2077 // associated classes to be considered. The sets of namespaces and
2078 // classes is determined entirely by the types of the function
2079 // arguments (and the namespace of any template template
2080 // argument). Typedef names and using-declarations used to specify
2081 // the types do not contribute to this set. The sets of namespaces
2082 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00002083
Chris Lattner5f9e2722011-07-23 10:55:15 +00002084 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00002085 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2086
Douglas Gregorfa047642009-02-04 00:32:51 +00002087 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00002088 switch (T->getTypeClass()) {
2089
2090#define TYPE(Class, Base)
2091#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2092#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2093#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2094#define ABSTRACT_TYPE(Class, Base)
2095#include "clang/AST/TypeNodes.def"
2096 // T is canonical. We can also ignore dependent types because
2097 // we don't need to do ADL at the definition point, but if we
2098 // wanted to implement template export (or if we find some other
2099 // use for associated classes and namespaces...) this would be
2100 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00002101 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002102
John McCallfa4edcf2010-05-28 06:08:54 +00002103 // -- If T is a pointer to U or an array of U, its associated
2104 // namespaces and classes are those associated with U.
2105 case Type::Pointer:
2106 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2107 continue;
2108 case Type::ConstantArray:
2109 case Type::IncompleteArray:
2110 case Type::VariableArray:
2111 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2112 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002113
John McCallfa4edcf2010-05-28 06:08:54 +00002114 // -- If T is a fundamental type, its associated sets of
2115 // namespaces and classes are both empty.
2116 case Type::Builtin:
2117 break;
2118
2119 // -- If T is a class type (including unions), its associated
2120 // classes are: the class itself; the class of which it is a
2121 // member, if any; and its direct and indirect base
2122 // classes. Its associated namespaces are the namespaces in
2123 // which its associated classes are defined.
2124 case Type::Record: {
2125 CXXRecordDecl *Class
2126 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002127 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00002128 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002129 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00002130
John McCallfa4edcf2010-05-28 06:08:54 +00002131 // -- If T is an enumeration type, its associated namespace is
2132 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002133 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00002134 // it has no associated class.
2135 case Type::Enum: {
2136 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002137
John McCallfa4edcf2010-05-28 06:08:54 +00002138 DeclContext *Ctx = Enum->getDeclContext();
2139 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002140 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002141
John McCallfa4edcf2010-05-28 06:08:54 +00002142 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002143 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002144
John McCallfa4edcf2010-05-28 06:08:54 +00002145 break;
2146 }
2147
2148 // -- If T is a function type, its associated namespaces and
2149 // classes are those associated with the function parameter
2150 // types and those associated with the return type.
2151 case Type::FunctionProto: {
2152 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2153 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2154 ArgEnd = Proto->arg_type_end();
2155 Arg != ArgEnd; ++Arg)
2156 Queue.push_back(Arg->getTypePtr());
2157 // fallthrough
2158 }
2159 case Type::FunctionNoProto: {
2160 const FunctionType *FnType = cast<FunctionType>(T);
2161 T = FnType->getResultType().getTypePtr();
2162 continue;
2163 }
2164
2165 // -- If T is a pointer to a member function of a class X, its
2166 // associated namespaces and classes are those associated
2167 // with the function parameter types and return type,
2168 // together with those associated with X.
2169 //
2170 // -- If T is a pointer to a data member of class X, its
2171 // associated namespaces and classes are those associated
2172 // with the member type together with those associated with
2173 // X.
2174 case Type::MemberPointer: {
2175 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2176
2177 // Queue up the class type into which this points.
2178 Queue.push_back(MemberPtr->getClass());
2179
2180 // And directly continue with the pointee type.
2181 T = MemberPtr->getPointeeType().getTypePtr();
2182 continue;
2183 }
2184
2185 // As an extension, treat this like a normal pointer.
2186 case Type::BlockPointer:
2187 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2188 continue;
2189
2190 // References aren't covered by the standard, but that's such an
2191 // obvious defect that we cover them anyway.
2192 case Type::LValueReference:
2193 case Type::RValueReference:
2194 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2195 continue;
2196
2197 // These are fundamental types.
2198 case Type::Vector:
2199 case Type::ExtVector:
2200 case Type::Complex:
2201 break;
2202
Richard Smithdc7a4f52013-04-30 13:56:41 +00002203 // Non-deduced auto types only get here for error cases.
2204 case Type::Auto:
2205 break;
2206
Douglas Gregorf25760e2011-04-12 01:02:45 +00002207 // If T is an Objective-C object or interface type, or a pointer to an
2208 // object or interface type, the associated namespace is the global
2209 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002210 case Type::ObjCObject:
2211 case Type::ObjCInterface:
2212 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002213 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002214 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002215
2216 // Atomic types are just wrappers; use the associations of the
2217 // contained type.
2218 case Type::Atomic:
2219 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2220 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002221 }
2222
2223 if (Queue.empty()) break;
2224 T = Queue.back();
2225 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002226 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002227}
2228
2229/// \brief Find the associated classes and namespaces for
2230/// argument-dependent lookup for a call with the given set of
2231/// arguments.
2232///
2233/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002234/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002235/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm834c0582013-08-09 18:02:13 +00002236void Sema::FindAssociatedClassesAndNamespaces(
2237 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2238 AssociatedNamespaceSet &AssociatedNamespaces,
2239 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002240 AssociatedNamespaces.clear();
2241 AssociatedClasses.clear();
2242
John McCall42f48fb2012-08-24 20:38:34 +00002243 AssociatedLookup Result(*this, InstantiationLoc,
2244 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002245
Douglas Gregorfa047642009-02-04 00:32:51 +00002246 // C++ [basic.lookup.koenig]p2:
2247 // For each argument type T in the function call, there is a set
2248 // of zero or more associated namespaces and a set of zero or more
2249 // associated classes to be considered. The sets of namespaces and
2250 // classes is determined entirely by the types of the function
2251 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002252 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002253 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002254 Expr *Arg = Args[ArgIdx];
2255
2256 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002257 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002258 continue;
2259 }
2260
2261 // [...] In addition, if the argument is the name or address of a
2262 // set of overloaded functions and/or function templates, its
2263 // associated classes and namespaces are the union of those
2264 // associated with each of the members of the set: the namespace
2265 // in which the function or function template is defined and the
2266 // classes and namespaces associated with its (non-dependent)
2267 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002268 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002269 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002270 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002271 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002272
John McCallc7e04da2010-05-28 18:45:08 +00002273 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2274 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002275
John McCallc7e04da2010-05-28 18:45:08 +00002276 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2277 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002278 // Look through any using declarations to find the underlying function.
2279 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002280
Chandler Carruthbd647292009-12-29 06:17:27 +00002281 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2282 if (!FDecl)
2283 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002284
2285 // Add the classes and namespaces associated with the parameter
2286 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002287 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002288 }
2289 }
2290}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002291
2292/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2293/// an acceptable non-member overloaded operator for a call whose
2294/// arguments have types T1 (and, if non-empty, T2). This routine
2295/// implements the check in C++ [over.match.oper]p3b2 concerning
2296/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002297static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002298IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2299 QualType T1, QualType T2,
2300 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002301 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2302 return true;
2303
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002304 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2305 return true;
2306
John McCall183700f2009-09-21 23:43:11 +00002307 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002308 if (Proto->getNumArgs() < 1)
2309 return false;
2310
2311 if (T1->isEnumeralType()) {
2312 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002313 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002314 return true;
2315 }
2316
2317 if (Proto->getNumArgs() < 2)
2318 return false;
2319
2320 if (!T2.isNull() && T2->isEnumeralType()) {
2321 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002322 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002323 return true;
2324 }
2325
2326 return false;
2327}
2328
John McCall7d384dd2009-11-18 07:57:50 +00002329NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002330 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002331 LookupNameKind NameKind,
2332 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002333 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002334 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002335 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002336}
2337
Douglas Gregor6e378de2009-04-23 23:18:26 +00002338/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002339ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002340 SourceLocation IdLoc,
2341 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002342 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002343 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002344 return cast_or_null<ObjCProtocolDecl>(D);
2345}
2346
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002347void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002348 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002349 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002350 // C++ [over.match.oper]p3:
2351 // -- The set of non-member candidates is the result of the
2352 // unqualified lookup of operator@ in the context of the
2353 // expression according to the usual rules for name lookup in
2354 // unqualified function calls (3.4.2) except that all member
2355 // functions are ignored. However, if no operand has a class
2356 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002357 // that have a first parameter of type T1 or "reference to
2358 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002359 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002360 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002361 // when T2 is an enumeration type, are candidate functions.
2362 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002363 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2364 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002366 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2367
John McCallf36e02d2009-10-09 21:13:30 +00002368 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002369 return;
2370
2371 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2372 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002373 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2374 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002375 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002376 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002377 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002378 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002379 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002380 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002381 // later?
2382 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002383 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002384 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002385 }
2386}
2387
Sean Huntc39b6bc2011-06-24 02:11:39 +00002388Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002389 CXXSpecialMember SM,
2390 bool ConstArg,
2391 bool VolatileArg,
2392 bool RValueThis,
2393 bool ConstThis,
2394 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002395 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002396 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002397 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002398 if (RValueThis || ConstThis || VolatileThis)
2399 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2400 "constructors and destructors always have unqualified lvalue this");
2401 if (ConstArg || VolatileArg)
2402 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2403 "parameter-less special members can't have qualified arguments");
2404
2405 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002406 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002407 ID.AddInteger(SM);
2408 ID.AddInteger(ConstArg);
2409 ID.AddInteger(VolatileArg);
2410 ID.AddInteger(RValueThis);
2411 ID.AddInteger(ConstThis);
2412 ID.AddInteger(VolatileThis);
2413
2414 void *InsertPoint;
2415 SpecialMemberOverloadResult *Result =
2416 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2417
2418 // This was already cached
2419 if (Result)
2420 return Result;
2421
Sean Hunt30543582011-06-07 00:11:58 +00002422 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2423 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002424 SpecialMemberCache.InsertNode(Result, InsertPoint);
2425
2426 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002427 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002428 DeclareImplicitDestructor(RD);
2429 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002430 assert(DD && "record without a destructor");
2431 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002432 Result->setKind(DD->isDeleted() ?
2433 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002434 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002435 return Result;
2436 }
2437
Sean Huntb320e0c2011-06-10 03:50:41 +00002438 // Prepare for overload resolution. Here we construct a synthetic argument
2439 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002440 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002441 DeclarationName Name;
2442 Expr *Arg = 0;
2443 unsigned NumArgs;
2444
Richard Smith704c8f72012-04-20 18:46:14 +00002445 QualType ArgType = CanTy;
2446 ExprValueKind VK = VK_LValue;
2447
Sean Huntb320e0c2011-06-10 03:50:41 +00002448 if (SM == CXXDefaultConstructor) {
2449 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2450 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002451 if (RD->needsImplicitDefaultConstructor())
2452 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002453 } else {
2454 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2455 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002456 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002457 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002458 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002459 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002460 } else {
2461 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002462 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002463 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002464 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002465 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002466 }
2467
Sean Huntb320e0c2011-06-10 03:50:41 +00002468 if (ConstArg)
2469 ArgType.addConst();
2470 if (VolatileArg)
2471 ArgType.addVolatile();
2472
2473 // This isn't /really/ specified by the standard, but it's implied
2474 // we should be working from an RValue in the case of move to ensure
2475 // that we prefer to bind to rvalue references, and an LValue in the
2476 // case of copy to ensure we don't bind to rvalue references.
2477 // Possibly an XValue is actually correct in the case of move, but
2478 // there is no semantic difference for class types in this restricted
2479 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002480 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002481 VK = VK_LValue;
2482 else
2483 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002484 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002485
Richard Smith704c8f72012-04-20 18:46:14 +00002486 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2487
2488 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002489 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002490 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002491 }
2492
2493 // Create the object argument
2494 QualType ThisTy = CanTy;
2495 if (ConstThis)
2496 ThisTy.addConst();
2497 if (VolatileThis)
2498 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002499 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002500 OpaqueValueExpr(SourceLocation(), ThisTy,
2501 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002502
2503 // Now we perform lookup on the name we computed earlier and do overload
2504 // resolution. Lookup is only performed directly into the class since there
2505 // will always be a (possibly implicit) declaration to shadow any others.
2506 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002507 DeclContext::lookup_result R = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002508
David Blaikie3bc93e32012-12-19 00:45:41 +00002509 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002510 "lookup for a constructor or assignment operator was empty");
David Blaikie3bc93e32012-12-19 00:45:41 +00002511 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002512 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002513
Sean Huntc39b6bc2011-06-24 02:11:39 +00002514 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002515 continue;
2516
Sean Huntc39b6bc2011-06-24 02:11:39 +00002517 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2518 // FIXME: [namespace.udecl]p15 says that we should only consider a
2519 // using declaration here if it does not match a declaration in the
2520 // derived class. We do not implement this correctly in other cases
2521 // either.
2522 Cand = U->getTargetDecl();
2523
2524 if (Cand->isInvalidDecl())
2525 continue;
2526 }
2527
2528 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002529 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002530 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002531 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2532 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002533 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002534 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2535 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002536 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002537 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002538 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2539 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002540 RD, 0, ThisTy, Classification,
2541 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002542 OCS, true);
2543 else
2544 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002545 0, llvm::makeArrayRef(&Arg, NumArgs),
2546 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002547 } else {
2548 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002549 }
2550 }
2551
2552 OverloadCandidateSet::iterator Best;
2553 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2554 case OR_Success:
2555 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002556 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002557 break;
2558
2559 case OR_Deleted:
2560 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002561 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002562 break;
2563
2564 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002565 Result->setMethod(0);
2566 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2567 break;
2568
Sean Huntb320e0c2011-06-10 03:50:41 +00002569 case OR_No_Viable_Function:
2570 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002571 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002572 break;
2573 }
2574
2575 return Result;
2576}
2577
2578/// \brief Look up the default constructor for the given class.
2579CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002580 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002581 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2582 false, false);
2583
2584 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002585}
2586
Sean Hunt661c67a2011-06-21 23:42:56 +00002587/// \brief Look up the copying constructor for the given class.
2588CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002589 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002590 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2591 "non-const, non-volatile qualifiers for copy ctor arg");
2592 SpecialMemberOverloadResult *Result =
2593 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2594 Quals & Qualifiers::Volatile, false, false, false);
2595
Sean Huntc530d172011-06-10 04:44:37 +00002596 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2597}
2598
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002599/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002600CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2601 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002602 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002603 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2604 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002605
2606 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2607}
2608
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002609/// \brief Look up the constructors for the given class.
2610DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002611 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002612 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002613 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002614 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002615 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002616 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002617 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002618 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002619 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002620
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002621 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2622 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2623 return Class->lookup(Name);
2624}
2625
Sean Hunt661c67a2011-06-21 23:42:56 +00002626/// \brief Look up the copying assignment operator for the given class.
2627CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2628 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002629 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002630 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2631 "non-const, non-volatile qualifiers for copy assignment arg");
2632 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2633 "non-const, non-volatile qualifiers for copy assignment this");
2634 SpecialMemberOverloadResult *Result =
2635 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2636 Quals & Qualifiers::Volatile, RValueThis,
2637 ThisQuals & Qualifiers::Const,
2638 ThisQuals & Qualifiers::Volatile);
2639
Sean Hunt661c67a2011-06-21 23:42:56 +00002640 return Result->getMethod();
2641}
2642
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002643/// \brief Look up the moving assignment operator for the given class.
2644CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002645 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002646 bool RValueThis,
2647 unsigned ThisQuals) {
2648 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2649 "non-const, non-volatile qualifiers for copy assignment this");
2650 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002651 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2652 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002653 ThisQuals & Qualifiers::Const,
2654 ThisQuals & Qualifiers::Volatile);
2655
2656 return Result->getMethod();
2657}
2658
Douglas Gregordb89f282010-07-01 22:47:18 +00002659/// \brief Look for the destructor of the given class.
2660///
Sean Huntc5c9b532011-06-03 21:10:40 +00002661/// During semantic analysis, this routine should be used in lieu of
2662/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002663///
2664/// \returns The destructor for this class.
2665CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002666 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2667 false, false, false,
2668 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002669}
2670
Richard Smith36f5cfe2012-03-09 08:00:36 +00002671/// LookupLiteralOperator - Determine which literal operator should be used for
2672/// a user-defined literal, per C++11 [lex.ext].
2673///
2674/// Normal overload resolution is not used to select which literal operator to
2675/// call for a user-defined literal. Look up the provided literal operator name,
2676/// and filter the results to the appropriate set for the given argument types.
2677Sema::LiteralOperatorLookupResult
2678Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2679 ArrayRef<QualType> ArgTys,
2680 bool AllowRawAndTemplate) {
2681 LookupName(R, S);
2682 assert(R.getResultKind() != LookupResult::Ambiguous &&
2683 "literal operator lookup can't be ambiguous");
2684
2685 // Filter the lookup results appropriately.
2686 LookupResult::Filter F = R.makeFilter();
2687
2688 bool FoundTemplate = false;
2689 bool FoundRaw = false;
2690 bool FoundExactMatch = false;
2691
2692 while (F.hasNext()) {
2693 Decl *D = F.next();
2694 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2695 D = USD->getTargetDecl();
2696
2697 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2698 bool IsRaw = false;
2699 bool IsExactMatch = false;
2700
Douglas Gregor7e0c2272013-04-10 05:18:00 +00002701 // If the declaration we found is invalid, skip it.
2702 if (D->isInvalidDecl()) {
2703 F.erase();
2704 continue;
2705 }
2706
Richard Smith36f5cfe2012-03-09 08:00:36 +00002707 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2708 if (FD->getNumParams() == 1 &&
2709 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2710 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002711 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002712 IsExactMatch = true;
2713 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2714 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2715 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2716 IsExactMatch = false;
2717 break;
2718 }
2719 }
2720 }
2721 }
2722
2723 if (IsExactMatch) {
2724 FoundExactMatch = true;
2725 AllowRawAndTemplate = false;
2726 if (FoundRaw || FoundTemplate) {
2727 // Go through again and remove the raw and template decls we've
2728 // already found.
2729 F.restart();
2730 FoundRaw = FoundTemplate = false;
2731 }
2732 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2733 FoundTemplate |= IsTemplate;
2734 FoundRaw |= IsRaw;
2735 } else {
2736 F.erase();
2737 }
2738 }
2739
2740 F.done();
2741
2742 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2743 // parameter type, that is used in preference to a raw literal operator
2744 // or literal operator template.
2745 if (FoundExactMatch)
2746 return LOLR_Cooked;
2747
2748 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2749 // operator template, but not both.
2750 if (FoundRaw && FoundTemplate) {
2751 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2752 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2753 Decl *D = *I;
2754 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2755 D = USD->getTargetDecl();
2756 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2757 D = FunTmpl->getTemplatedDecl();
2758 NoteOverloadCandidate(cast<FunctionDecl>(D));
2759 }
2760 return LOLR_Error;
2761 }
2762
2763 if (FoundRaw)
2764 return LOLR_Raw;
2765
2766 if (FoundTemplate)
2767 return LOLR_Template;
2768
2769 // Didn't find anything we could use.
2770 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2771 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2772 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2773 return LOLR_Error;
2774}
2775
John McCall7edb5fd2010-01-26 07:16:45 +00002776void ADLResult::insert(NamedDecl *New) {
2777 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2778
2779 // If we haven't yet seen a decl for this key, or the last decl
2780 // was exactly this one, we're done.
2781 if (Old == 0 || Old == New) {
2782 Old = New;
2783 return;
2784 }
2785
2786 // Otherwise, decide which is a more recent redeclaration.
2787 FunctionDecl *OldFD, *NewFD;
2788 if (isa<FunctionTemplateDecl>(New)) {
2789 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2790 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2791 } else {
2792 OldFD = cast<FunctionDecl>(Old);
2793 NewFD = cast<FunctionDecl>(New);
2794 }
2795
2796 FunctionDecl *Cursor = NewFD;
2797 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002798 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002799
2800 // If we got to the end without finding OldFD, OldFD is the newer
2801 // declaration; leave things as they are.
2802 if (!Cursor) return;
2803
2804 // If we do find OldFD, then NewFD is newer.
2805 if (Cursor == OldFD) break;
2806
2807 // Otherwise, keep looking.
2808 }
2809
2810 Old = New;
2811}
2812
Sebastian Redl644be852009-10-23 19:23:15 +00002813void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm834c0582013-08-09 18:02:13 +00002814 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002815 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002816 // Find all of the associated namespaces and classes based on the
2817 // arguments we have.
2818 AssociatedNamespaceSet AssociatedNamespaces;
2819 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002820 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002821 AssociatedNamespaces,
2822 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002823
Sebastian Redl644be852009-10-23 19:23:15 +00002824 QualType T1, T2;
2825 if (Operator) {
2826 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002827 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002828 T2 = Args[1]->getType();
2829 }
2830
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002831 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002832 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2833 // and let Y be the lookup set produced by argument dependent
2834 // lookup (defined as follows). If X contains [...] then Y is
2835 // empty. Otherwise Y is the set of declarations found in the
2836 // namespaces associated with the argument types as described
2837 // below. The set of declarations found by the lookup of the name
2838 // is the union of X and Y.
2839 //
2840 // Here, we compute Y and add its members to the overloaded
2841 // candidate set.
2842 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002843 NSEnd = AssociatedNamespaces.end();
2844 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002845 // When considering an associated namespace, the lookup is the
2846 // same as the lookup performed when the associated namespace is
2847 // used as a qualifier (3.4.3.2) except that:
2848 //
2849 // -- Any using-directives in the associated namespace are
2850 // ignored.
2851 //
John McCall6ff07852009-08-07 22:18:02 +00002852 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002853 // associated classes are visible within their respective
2854 // namespaces even if they are not visible during an ordinary
2855 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002856 DeclContext::lookup_result R = (*NS)->lookup(Name);
2857 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2858 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002859 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002860 // If the only declaration here is an ordinary friend, consider
2861 // it only if it was declared in an associated classes.
2862 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
Richard Smith22050f22013-07-17 23:53:16 +00002863 bool DeclaredInAssociatedClass = false;
2864 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2865 DeclContext *LexDC = DI->getLexicalDeclContext();
2866 if (isa<CXXRecordDecl>(LexDC) &&
2867 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2868 DeclaredInAssociatedClass = true;
2869 break;
2870 }
2871 }
2872 if (!DeclaredInAssociatedClass)
John McCall3f9a8a62009-08-11 06:59:38 +00002873 continue;
2874 }
Mike Stump1eb44332009-09-09 15:08:12 +00002875
John McCalla113e722010-01-26 06:04:06 +00002876 if (isa<UsingShadowDecl>(D))
2877 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002878
John McCalla113e722010-01-26 06:04:06 +00002879 if (isa<FunctionDecl>(D)) {
2880 if (Operator &&
2881 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2882 T1, T2, Context))
2883 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002884 } else if (!isa<FunctionTemplateDecl>(D))
2885 continue;
2886
2887 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002888 }
2889 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002890}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002891
2892//----------------------------------------------------------------------------
2893// Search for all visible declarations.
2894//----------------------------------------------------------------------------
2895VisibleDeclConsumer::~VisibleDeclConsumer() { }
2896
2897namespace {
2898
2899class ShadowContextRAII;
2900
2901class VisibleDeclsRecord {
2902public:
2903 /// \brief An entry in the shadow map, which is optimized to store a
2904 /// single declaration (the common case) but can also store a list
2905 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002906 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002907
2908private:
2909 /// \brief A mapping from declaration names to the declarations that have
2910 /// this name within a particular scope.
2911 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2912
2913 /// \brief A list of shadow maps, which is used to model name hiding.
2914 std::list<ShadowMap> ShadowMaps;
2915
2916 /// \brief The declaration contexts we have already visited.
2917 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2918
2919 friend class ShadowContextRAII;
2920
2921public:
2922 /// \brief Determine whether we have already visited this context
2923 /// (and, if not, note that we are going to visit that context now).
2924 bool visitedContext(DeclContext *Ctx) {
2925 return !VisitedContexts.insert(Ctx);
2926 }
2927
Douglas Gregor8071e422010-08-15 06:18:01 +00002928 bool alreadyVisitedContext(DeclContext *Ctx) {
2929 return VisitedContexts.count(Ctx);
2930 }
2931
Douglas Gregor546be3c2009-12-30 17:04:44 +00002932 /// \brief Determine whether the given declaration is hidden in the
2933 /// current scope.
2934 ///
2935 /// \returns the declaration that hides the given declaration, or
2936 /// NULL if no such declaration exists.
2937 NamedDecl *checkHidden(NamedDecl *ND);
2938
2939 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002940 void add(NamedDecl *ND) {
2941 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2942 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002943};
2944
2945/// \brief RAII object that records when we've entered a shadow context.
2946class ShadowContextRAII {
2947 VisibleDeclsRecord &Visible;
2948
2949 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2950
2951public:
2952 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2953 Visible.ShadowMaps.push_back(ShadowMap());
2954 }
2955
2956 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002957 Visible.ShadowMaps.pop_back();
2958 }
2959};
2960
2961} // end anonymous namespace
2962
Douglas Gregor546be3c2009-12-30 17:04:44 +00002963NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002964 // Look through using declarations.
2965 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002966
Douglas Gregor546be3c2009-12-30 17:04:44 +00002967 unsigned IDNS = ND->getIdentifierNamespace();
2968 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2969 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2970 SM != SMEnd; ++SM) {
2971 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2972 if (Pos == SM->end())
2973 continue;
2974
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002975 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002976 IEnd = Pos->second.end();
2977 I != IEnd; ++I) {
2978 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002979 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002980 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002981 Decl::IDNS_ObjCProtocol)))
2982 continue;
2983
2984 // Protocols are in distinct namespaces from everything else.
2985 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2986 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2987 (*I)->getIdentifierNamespace() != IDNS)
2988 continue;
2989
Douglas Gregor0cc84042010-01-14 15:47:35 +00002990 // Functions and function templates in the same scope overload
2991 // rather than hide. FIXME: Look for hiding based on function
2992 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002993 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002994 ND->isFunctionOrFunctionTemplate() &&
2995 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002996 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002997
Douglas Gregor546be3c2009-12-30 17:04:44 +00002998 // We've found a declaration that hides this one.
2999 return *I;
3000 }
3001 }
3002
3003 return 0;
3004}
3005
3006static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3007 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003008 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00003009 VisibleDeclConsumer &Consumer,
3010 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00003011 if (!Ctx)
3012 return;
3013
Douglas Gregor546be3c2009-12-30 17:04:44 +00003014 // Make sure we don't visit the same context twice.
3015 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3016 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003017
Douglas Gregor4923aa22010-07-02 20:37:36 +00003018 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3019 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3020
Douglas Gregor546be3c2009-12-30 17:04:44 +00003021 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00003022 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
3023 LEnd = Ctx->lookups_end();
3024 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003025 DeclContext::lookup_result R = *L;
3026 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3027 ++I) {
3028 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00003029 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003030 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003031 Visited.add(ND);
3032 }
Douglas Gregor70c23352010-12-09 21:44:02 +00003033 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003034 }
3035 }
3036
3037 // Traverse using directives for qualified name lookup.
3038 if (QualifiedNameLookup) {
3039 ShadowContextRAII Shadow(Visited);
3040 DeclContext::udir_iterator I, E;
3041 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003042 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003043 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003044 }
3045 }
3046
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003047 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003048 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00003049 if (!Record->hasDefinition())
3050 return;
3051
Douglas Gregor546be3c2009-12-30 17:04:44 +00003052 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
3053 BEnd = Record->bases_end();
3054 B != BEnd; ++B) {
3055 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003056
Douglas Gregor546be3c2009-12-30 17:04:44 +00003057 // Don't look into dependent bases, because name lookup can't look
3058 // there anyway.
3059 if (BaseType->isDependentType())
3060 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003061
Douglas Gregor546be3c2009-12-30 17:04:44 +00003062 const RecordType *Record = BaseType->getAs<RecordType>();
3063 if (!Record)
3064 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003065
Douglas Gregor546be3c2009-12-30 17:04:44 +00003066 // FIXME: It would be nice to be able to determine whether referencing
3067 // a particular member would be ambiguous. For example, given
3068 //
3069 // struct A { int member; };
3070 // struct B { int member; };
3071 // struct C : A, B { };
3072 //
3073 // void f(C *c) { c->### }
3074 //
3075 // accessing 'member' would result in an ambiguity. However, we
3076 // could be smart enough to qualify the member with the base
3077 // class, e.g.,
3078 //
3079 // c->B::member
3080 //
3081 // or
3082 //
3083 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003084
Douglas Gregor546be3c2009-12-30 17:04:44 +00003085 // Find results in this base class (and its bases).
3086 ShadowContextRAII Shadow(Visited);
3087 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003088 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003089 }
3090 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003091
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003092 // Traverse the contexts of Objective-C classes.
3093 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3094 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00003095 for (ObjCInterfaceDecl::visible_categories_iterator
3096 Cat = IFace->visible_categories_begin(),
3097 CatEnd = IFace->visible_categories_end();
3098 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003099 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00003100 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003101 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003102 }
3103
3104 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003105 for (ObjCInterfaceDecl::all_protocol_iterator
3106 I = IFace->all_referenced_protocol_begin(),
3107 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003108 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003109 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003110 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003111 }
3112
3113 // Traverse the superclass.
3114 if (IFace->getSuperClass()) {
3115 ShadowContextRAII Shadow(Visited);
3116 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003117 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003118 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003119
Douglas Gregorc220a182010-04-19 18:02:19 +00003120 // If there is an implementation, traverse it. We do this to find
3121 // synthesized ivars.
3122 if (IFace->getImplementation()) {
3123 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003124 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00003125 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00003126 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003127 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3128 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3129 E = Protocol->protocol_end(); I != E; ++I) {
3130 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003131 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003132 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003133 }
3134 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3135 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3136 E = Category->protocol_end(); I != E; ++I) {
3137 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003138 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003139 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003141
Douglas Gregorc220a182010-04-19 18:02:19 +00003142 // If there is an implementation, traverse it.
3143 if (Category->getImplementation()) {
3144 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003145 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00003146 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003147 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003148 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003149}
3150
3151static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3152 UnqualUsingDirectiveSet &UDirs,
3153 VisibleDeclConsumer &Consumer,
3154 VisibleDeclsRecord &Visited) {
3155 if (!S)
3156 return;
3157
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003158 if (!S->getEntity() ||
3159 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00003160 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00003161 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3162 // Walk through the declarations in this Scope.
3163 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3164 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003165 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003166 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003167 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003168 Visited.add(ND);
3169 }
3170 }
3171 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003172
Douglas Gregor711be1e2010-03-15 14:33:29 +00003173 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003174 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003175 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003176 // Look into this scope's declaration context, along with any of its
3177 // parent lookup contexts (e.g., enclosing classes), up to the point
3178 // where we hit the context stored in the next outer scope.
3179 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003180 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003181
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003182 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003183 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003184 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3185 if (Method->isInstanceMethod()) {
3186 // For instance methods, look for ivars in the method's interface.
3187 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3188 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003189 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003190 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00003191 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003192 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003193 }
3194
3195 // We've already performed all of the name lookup that we need
3196 // to for Objective-C methods; the next context will be the
3197 // outer scope.
3198 break;
3199 }
3200
Douglas Gregor546be3c2009-12-30 17:04:44 +00003201 if (Ctx->isFunctionOrMethod())
3202 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003203
3204 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003205 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003206 }
3207 } else if (!S->getParent()) {
3208 // Look into the translation unit scope. We walk through the translation
3209 // unit's declaration context, because the Scope itself won't have all of
3210 // the declarations if we loaded a precompiled header.
3211 // FIXME: We would like the translation unit's Scope object to point to the
3212 // translation unit, so we don't need this special "if" branch. However,
3213 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003215 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003216 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003217 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003219 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003220 }
3221
Douglas Gregor546be3c2009-12-30 17:04:44 +00003222 if (Entity) {
3223 // Lookup visible declarations in any namespaces found by using
3224 // directives.
3225 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3226 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3227 for (; UI != UEnd; ++UI)
3228 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003229 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003230 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003231 }
3232
3233 // Lookup names in the parent scope.
3234 ShadowContextRAII Shadow(Visited);
3235 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3236}
3237
3238void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003239 VisibleDeclConsumer &Consumer,
3240 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003241 // Determine the set of using directives available during
3242 // unqualified name lookup.
3243 Scope *Initial = S;
3244 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003245 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003246 // Find the first namespace or translation-unit scope.
3247 while (S && !isNamespaceOrTranslationUnitScope(S))
3248 S = S->getParent();
3249
3250 UDirs.visitScopeChain(Initial, S);
3251 }
3252 UDirs.done();
3253
3254 // Look for visible declarations.
3255 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3256 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003257 if (!IncludeGlobalScope)
3258 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003259 ShadowContextRAII Shadow(Visited);
3260 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3261}
3262
3263void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003264 VisibleDeclConsumer &Consumer,
3265 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003266 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3267 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003268 if (!IncludeGlobalScope)
3269 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003270 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003271 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003272 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003273}
3274
Chris Lattner4ae493c2011-02-18 02:08:43 +00003275/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003276/// If GnuLabelLoc is a valid source location, then this is a definition
3277/// of an __label__ label name, otherwise it is a normal label definition
3278/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003279LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003280 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003281 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003282 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003283
3284 if (GnuLabelLoc.isValid()) {
3285 // Local label definitions always shadow existing labels.
3286 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3287 Scope *S = CurScope;
3288 PushOnScopeChains(Res, S, true);
3289 return cast<LabelDecl>(Res);
3290 }
3291
3292 // Not a GNU local label.
3293 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3294 // If we found a label, check to see if it is in the same context as us.
3295 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003296 if (Res && Res->getDeclContext() != CurContext)
3297 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003298 if (Res == 0) {
3299 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003300 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3301 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003302 assert(S && "Not in a function?");
3303 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003304 }
Chris Lattner337e5502011-02-18 01:27:55 +00003305 return cast<LabelDecl>(Res);
3306}
3307
3308//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003309// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003310//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003311
3312namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003313
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003314typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003315typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003316typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003317
3318static const unsigned MaxTypoDistanceResultSets = 5;
3319
Douglas Gregor546be3c2009-12-30 17:04:44 +00003320class TypoCorrectionConsumer : public VisibleDeclConsumer {
3321 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003322 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003323
3324 /// \brief The results found that have the smallest edit distance
3325 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003326 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003327 /// The pointer value being set to the current DeclContext indicates
3328 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003329 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003330
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003331 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003332
Douglas Gregor546be3c2009-12-30 17:04:44 +00003333public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003334 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003335 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003336 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003337
Erik Verbruggend1205962011-10-06 07:27:49 +00003338 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3339 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003340 void FoundName(StringRef Name);
3341 void addKeywordResult(StringRef Keyword);
3342 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003343 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003344 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003345
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003346 typedef TypoResultsMap::iterator result_iterator;
3347 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003348 distance_iterator begin() { return CorrectionResults.begin(); }
3349 distance_iterator end() { return CorrectionResults.end(); }
3350 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3351 unsigned size() const { return CorrectionResults.size(); }
3352 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003353
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003354 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003355 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003356 }
3357
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003358 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003359 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003360 return (std::numeric_limits<unsigned>::max)();
3361
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003362 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003363 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003364 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003365
3366 TypoResultsMap &getBestResults() {
3367 return CorrectionResults.begin()->second;
3368 }
3369
Douglas Gregor546be3c2009-12-30 17:04:44 +00003370};
3371
3372}
3373
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003374void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003375 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003376 // Don't consider hidden names for typo correction.
3377 if (Hiding)
3378 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379
Douglas Gregor546be3c2009-12-30 17:04:44 +00003380 // Only consider entities with identifiers for names, ignoring
3381 // special names (constructors, overloaded operators, selectors,
3382 // etc.).
3383 IdentifierInfo *Name = ND->getIdentifier();
3384 if (!Name)
3385 return;
3386
Douglas Gregor95f42922010-10-14 22:11:03 +00003387 FoundName(Name->getName());
3388}
3389
Chris Lattner5f9e2722011-07-23 10:55:15 +00003390void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003391 // Use a simple length-based heuristic to determine the minimum possible
3392 // edit distance. If the minimum isn't good enough, bail out early.
3393 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003394 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003395 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003396
Douglas Gregora1194772010-10-19 22:14:33 +00003397 // Compute an upper bound on the allowable edit distance, so that the
3398 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003399 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003400
Douglas Gregor546be3c2009-12-30 17:04:44 +00003401 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003402 // entity, and add the identifier to the list of results.
3403 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003404}
3405
Chris Lattner5f9e2722011-07-23 10:55:15 +00003406void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003407 // Compute the edit distance between the typo and this keyword,
3408 // and add the keyword to the list of results.
3409 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003410}
3411
Chris Lattner5f9e2722011-07-23 10:55:15 +00003412void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003413 NamedDecl *ND,
3414 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003415 NestedNameSpecifier *NNS,
3416 bool isKeyword) {
3417 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3418 if (isKeyword) TC.makeKeyword();
3419 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003420}
3421
3422void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003423 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003424 TypoResultList &CList =
3425 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003426
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003427 if (!CList.empty() && !CList.back().isResolved())
3428 CList.pop_back();
3429 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3430 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3431 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3432 RI != RIEnd; ++RI) {
3433 // If the Correction refers to a decl already in the result list,
3434 // replace the existing result if the string representation of Correction
3435 // comes before the current result alphabetically, then stop as there is
3436 // nothing more to be done to add Correction to the candidate set.
3437 if (RI->getCorrectionDecl() == NewND) {
3438 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3439 *RI = Correction;
3440 return;
3441 }
3442 }
3443 }
3444 if (CList.empty() || Correction.isResolved())
3445 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003446
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003447 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3448 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003449}
3450
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003451// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3452// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3453// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3454static void getNestedNameSpecifierIdentifiers(
3455 NestedNameSpecifier *NNS,
3456 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3457 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3458 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3459 else
3460 Identifiers.clear();
3461
3462 const IdentifierInfo *II = NULL;
3463
3464 switch (NNS->getKind()) {
3465 case NestedNameSpecifier::Identifier:
3466 II = NNS->getAsIdentifier();
3467 break;
3468
3469 case NestedNameSpecifier::Namespace:
3470 if (NNS->getAsNamespace()->isAnonymousNamespace())
3471 return;
3472 II = NNS->getAsNamespace()->getIdentifier();
3473 break;
3474
3475 case NestedNameSpecifier::NamespaceAlias:
3476 II = NNS->getAsNamespaceAlias()->getIdentifier();
3477 break;
3478
3479 case NestedNameSpecifier::TypeSpecWithTemplate:
3480 case NestedNameSpecifier::TypeSpec:
3481 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3482 break;
3483
3484 case NestedNameSpecifier::Global:
3485 return;
3486 }
3487
3488 if (II)
3489 Identifiers.push_back(II);
3490}
3491
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003492namespace {
3493
3494class SpecifierInfo {
3495 public:
3496 DeclContext* DeclCtx;
3497 NestedNameSpecifier* NameSpecifier;
3498 unsigned EditDistance;
3499
3500 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3501 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3502};
3503
Chris Lattner5f9e2722011-07-23 10:55:15 +00003504typedef SmallVector<DeclContext*, 4> DeclContextList;
3505typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003506
3507class NamespaceSpecifierSet {
3508 ASTContext &Context;
3509 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003510 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3511 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003512 bool isSorted;
3513
3514 SpecifierInfoList Specifiers;
3515 llvm::SmallSetVector<unsigned, 4> Distances;
3516 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3517
3518 /// \brief Helper for building the list of DeclContexts between the current
3519 /// context and the top of the translation unit
3520 static DeclContextList BuildContextChain(DeclContext *Start);
3521
3522 void SortNamespaces();
3523
3524 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003525 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3526 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003527 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003528 isSorted(false) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003529 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3530 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3531 CurNameSpecifierIdentifiers);
3532 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003533 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003534 // context.
3535 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3536 CEnd = CurContextChain.rend();
3537 C != CEnd; ++C) {
3538 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3539 CurContextIdentifiers.push_back(ND->getIdentifier());
3540 }
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003541
3542 // Add the global context as a NestedNameSpecifier
3543 Distances.insert(1);
3544 DistanceMap[1].push_back(
3545 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3546 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003547 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003548
3549 /// \brief Add the namespace to the set, computing the corresponding
3550 /// NestedNameSpecifier and its distance in the process.
3551 void AddNamespace(NamespaceDecl *ND);
3552
3553 typedef SpecifierInfoList::iterator iterator;
3554 iterator begin() {
3555 if (!isSorted) SortNamespaces();
3556 return Specifiers.begin();
3557 }
3558 iterator end() { return Specifiers.end(); }
3559};
3560
3561}
3562
3563DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0db9d202013-04-08 21:55:21 +00003564 assert(Start && "Building a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003565 DeclContextList Chain;
3566 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3567 DC = DC->getLookupParent()) {
3568 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3569 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3570 !(ND && ND->isAnonymousNamespace()))
3571 Chain.push_back(DC->getPrimaryContext());
3572 }
3573 return Chain;
3574}
3575
3576void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003577 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003578 sortedDistances.append(Distances.begin(), Distances.end());
3579
3580 if (sortedDistances.size() > 1)
3581 std::sort(sortedDistances.begin(), sortedDistances.end());
3582
3583 Specifiers.clear();
Craig Topper09d19ef2013-07-04 03:08:24 +00003584 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3585 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003586 DI != DIEnd; ++DI) {
3587 SpecifierInfoList &SpecList = DistanceMap[*DI];
3588 Specifiers.append(SpecList.begin(), SpecList.end());
3589 }
3590
3591 isSorted = true;
3592}
3593
3594void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003595 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003596 NestedNameSpecifier *NNS = NULL;
3597 unsigned NumSpecifiers = 0;
3598 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003599 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003600
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003601 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003602 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3603 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003604 C != CEnd && !NamespaceDeclChain.empty() &&
3605 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003606 NamespaceDeclChain.pop_back();
3607 }
3608
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003609 // Add an explicit leading '::' specifier if needed.
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00003610 if (NamespaceDeclChain.empty()) {
3611 NamespaceDeclChain = FullNamespaceDeclChain;
3612 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3613 } else if (NamespaceDecl *ND =
3614 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003615 IdentifierInfo *Name = ND->getIdentifier();
3616 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3617 Name) != CurContextIdentifiers.end() ||
3618 std::find(CurNameSpecifierIdentifiers.begin(),
3619 CurNameSpecifierIdentifiers.end(),
3620 Name) != CurNameSpecifierIdentifiers.end()) {
3621 NamespaceDeclChain = FullNamespaceDeclChain;
3622 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3623 }
3624 }
3625
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003626 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3627 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3628 CEnd = NamespaceDeclChain.rend();
3629 C != CEnd; ++C) {
3630 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3631 if (ND) {
3632 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3633 ++NumSpecifiers;
3634 }
3635 }
3636
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003637 // If the built NestedNameSpecifier would be replacing an existing
3638 // NestedNameSpecifier, use the number of component identifiers that
3639 // would need to be changed as the edit distance instead of the number
3640 // of components in the built NestedNameSpecifier.
3641 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3642 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3643 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3644 NumSpecifiers = llvm::ComputeEditDistance(
Robert Wilhelm834c0582013-08-09 18:02:13 +00003645 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3646 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003647 }
3648
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003649 isSorted = false;
3650 Distances.insert(NumSpecifiers);
3651 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003652}
3653
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003654/// \brief Perform name lookup for a possible result for typo correction.
3655static void LookupPotentialTypoResult(Sema &SemaRef,
3656 LookupResult &Res,
3657 IdentifierInfo *Name,
3658 Scope *S, CXXScopeSpec *SS,
3659 DeclContext *MemberContext,
3660 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003661 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003662 Res.suppressDiagnostics();
3663 Res.clear();
3664 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003665 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003666 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003667 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003668 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3669 Res.addDecl(Ivar);
3670 Res.resolveKind();
3671 return;
3672 }
3673 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003674
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003675 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3676 Res.addDecl(Prop);
3677 Res.resolveKind();
3678 return;
3679 }
3680 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003681
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003682 SemaRef.LookupQualifiedName(Res, MemberContext);
3683 return;
3684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003685
3686 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003687 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003688
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003689 // Fake ivar lookup; this should really be part of
3690 // LookupParsedName.
3691 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3692 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003693 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003694 (Res.isSingleResult() &&
3695 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003696 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003697 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3698 Res.addDecl(IV);
3699 Res.resolveKind();
3700 }
3701 }
3702 }
3703}
3704
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003705/// \brief Add keywords to the consumer as possible typo corrections.
3706static void AddKeywordsToConsumer(Sema &SemaRef,
3707 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003708 Scope *S, CorrectionCandidateCallback &CCC,
3709 bool AfterNestedNameSpecifier) {
3710 if (AfterNestedNameSpecifier) {
3711 // For 'X::', we know exactly which keywords can appear next.
3712 Consumer.addKeywordResult("template");
3713 if (CCC.WantExpressionKeywords)
3714 Consumer.addKeywordResult("operator");
3715 return;
3716 }
3717
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003718 if (CCC.WantObjCSuper)
3719 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003720
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003721 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003722 // Add type-specifier keywords to the set of results.
Craig Topper3aa29df2013-07-15 08:24:27 +00003723 static const char *const CTypeSpecs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003724 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003725 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003726 "_Complex", "_Imaginary",
3727 // storage-specifiers as well
3728 "extern", "inline", "static", "typedef"
3729 };
3730
Craig Topperb9602322013-07-15 03:38:40 +00003731 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003732 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3733 Consumer.addKeywordResult(CTypeSpecs[I]);
3734
David Blaikie4e4d0842012-03-11 07:00:24 +00003735 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003736 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003737 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003738 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003739 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003740 Consumer.addKeywordResult("_Bool");
3741
David Blaikie4e4d0842012-03-11 07:00:24 +00003742 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003743 Consumer.addKeywordResult("class");
3744 Consumer.addKeywordResult("typename");
3745 Consumer.addKeywordResult("wchar_t");
3746
Richard Smith80ad52f2013-01-02 11:42:31 +00003747 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003748 Consumer.addKeywordResult("char16_t");
3749 Consumer.addKeywordResult("char32_t");
3750 Consumer.addKeywordResult("constexpr");
3751 Consumer.addKeywordResult("decltype");
3752 Consumer.addKeywordResult("thread_local");
3753 }
3754 }
3755
David Blaikie4e4d0842012-03-11 07:00:24 +00003756 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003757 Consumer.addKeywordResult("typeof");
3758 }
3759
David Blaikie4e4d0842012-03-11 07:00:24 +00003760 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003761 Consumer.addKeywordResult("const_cast");
3762 Consumer.addKeywordResult("dynamic_cast");
3763 Consumer.addKeywordResult("reinterpret_cast");
3764 Consumer.addKeywordResult("static_cast");
3765 }
3766
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003767 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003768 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003769 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003770 Consumer.addKeywordResult("false");
3771 Consumer.addKeywordResult("true");
3772 }
3773
David Blaikie4e4d0842012-03-11 07:00:24 +00003774 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topper3aa29df2013-07-15 08:24:27 +00003775 static const char *const CXXExprs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003776 "delete", "new", "operator", "throw", "typeid"
3777 };
Craig Topperb9602322013-07-15 03:38:40 +00003778 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003779 for (unsigned I = 0; I != NumCXXExprs; ++I)
3780 Consumer.addKeywordResult(CXXExprs[I]);
3781
3782 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3783 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3784 Consumer.addKeywordResult("this");
3785
Richard Smith80ad52f2013-01-02 11:42:31 +00003786 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003787 Consumer.addKeywordResult("alignof");
3788 Consumer.addKeywordResult("nullptr");
3789 }
3790 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003791
3792 if (SemaRef.getLangOpts().C11) {
3793 // FIXME: We should not suggest _Alignof if the alignof macro
3794 // is present.
3795 Consumer.addKeywordResult("_Alignof");
3796 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003797 }
3798
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003799 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003800 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3801 // Statements.
Craig Topper3aa29df2013-07-15 08:24:27 +00003802 static const char *const CStmts[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003803 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Topperb9602322013-07-15 03:38:40 +00003804 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003805 for (unsigned I = 0; I != NumCStmts; ++I)
3806 Consumer.addKeywordResult(CStmts[I]);
3807
David Blaikie4e4d0842012-03-11 07:00:24 +00003808 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003809 Consumer.addKeywordResult("catch");
3810 Consumer.addKeywordResult("try");
3811 }
3812
3813 if (S && S->getBreakParent())
3814 Consumer.addKeywordResult("break");
3815
3816 if (S && S->getContinueParent())
3817 Consumer.addKeywordResult("continue");
3818
3819 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3820 Consumer.addKeywordResult("case");
3821 Consumer.addKeywordResult("default");
3822 }
3823 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003824 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003825 Consumer.addKeywordResult("namespace");
3826 Consumer.addKeywordResult("template");
3827 }
3828
3829 if (S && S->isClassScope()) {
3830 Consumer.addKeywordResult("explicit");
3831 Consumer.addKeywordResult("friend");
3832 Consumer.addKeywordResult("mutable");
3833 Consumer.addKeywordResult("private");
3834 Consumer.addKeywordResult("protected");
3835 Consumer.addKeywordResult("public");
3836 Consumer.addKeywordResult("virtual");
3837 }
3838 }
3839
David Blaikie4e4d0842012-03-11 07:00:24 +00003840 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003841 Consumer.addKeywordResult("using");
3842
Richard Smith80ad52f2013-01-02 11:42:31 +00003843 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003844 Consumer.addKeywordResult("static_assert");
3845 }
3846 }
3847}
3848
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003849static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3850 TypoCorrection &Candidate) {
3851 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3852 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3853}
3854
Douglas Gregor546be3c2009-12-30 17:04:44 +00003855/// \brief Try to "correct" a typo in the source code by finding
3856/// visible declarations whose names are similar to the name that was
3857/// present in the source code.
3858///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003859/// \param TypoName the \c DeclarationNameInfo structure that contains
3860/// the name that was present in the source code along with its location.
3861///
3862/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003863///
3864/// \param S the scope in which name lookup occurs.
3865///
3866/// \param SS the nested-name-specifier that precedes the name we're
3867/// looking for, if present.
3868///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003869/// \param CCC A CorrectionCandidateCallback object that provides further
3870/// validation of typo correction candidates. It also provides flags for
3871/// determining the set of keywords permitted.
3872///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003873/// \param MemberContext if non-NULL, the context in which to look for
3874/// a member access expression.
3875///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003876/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003877/// the nested-name-specifier SS.
3878///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003879/// \param OPT when non-NULL, the search for visible declarations will
3880/// also walk the protocols in the qualified interfaces of \p OPT.
3881///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003882/// \returns a \c TypoCorrection containing the corrected name if the typo
3883/// along with information such as the \c NamedDecl where the corrected name
3884/// was declared, and any additional \c NestedNameSpecifier needed to access
3885/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3886TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3887 Sema::LookupNameKind LookupKind,
3888 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003889 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003890 DeclContext *MemberContext,
3891 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003892 const ObjCObjectPointerType *OPT) {
Kaelyn Uhrain70571f42013-08-12 19:54:38 +00003893 // Always let the ExternalSource have the first chance at correction, even
3894 // if we would otherwise have given up.
3895 if (ExternalSource) {
3896 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
3897 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
3898 return Correction;
3899 }
3900
David Blaikie4e4d0842012-03-11 07:00:24 +00003901 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003902 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003903
Francois Pichet4d604d62011-12-03 15:55:29 +00003904 // In Microsoft mode, don't perform typo correction in a template member
3905 // function dependent context because it interferes with the "lookup into
3906 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003907 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003908 isa<CXXMethodDecl>(CurContext))
3909 return TypoCorrection();
3910
Douglas Gregor546be3c2009-12-30 17:04:44 +00003911 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003912 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003913 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003914 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003915
3916 // If the scope specifier itself was invalid, don't try to correct
3917 // typos.
3918 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003919 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003920
3921 // Never try to correct typos during template deduction or
3922 // instantiation.
3923 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003924 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003925
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003926 // Don't try to correct 'super'.
3927 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3928 return TypoCorrection();
3929
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003930 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003931
3932 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003933
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003934 // If a callback object considers an empty typo correction candidate to be
3935 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003936 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003937 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003938
Douglas Gregoraaf87162010-04-14 20:04:41 +00003939 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003940 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003941 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003942 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003943 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003944
3945 // Look in qualified interfaces.
3946 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003947 for (ObjCObjectPointerType::qual_iterator
3948 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003949 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003950 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003951 }
3952 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003953 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3954 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003955 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003956
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003957 // Provide a stop gap for files that are just seriously broken. Trying
3958 // to correct all typos can turn into a HUGE performance penalty, causing
3959 // some files to take minutes to get rejected by the parser.
3960 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003961 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003962 ++TyposCorrected;
3963
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003964 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003965 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003966 IsUnqualifiedLookup = true;
3967 UnqualifiedTyposCorrectedMap::iterator Cached
3968 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003969 if (Cached != UnqualifiedTyposCorrected.end()) {
3970 // Add the cached value, unless it's a keyword or fails validation. In the
3971 // keyword case, we'll end up adding the keyword below.
3972 if (Cached->second) {
3973 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003974 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003975 Consumer.addCorrection(Cached->second);
3976 } else {
3977 // Only honor no-correction cache hits when a callback that will validate
3978 // correction candidates is not being used.
3979 if (!ValidatingCallback)
3980 return TypoCorrection();
3981 }
3982 }
3983 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003984 // Provide a stop gap for files that are just seriously broken. Trying
3985 // to correct all typos can turn into a HUGE performance penalty, causing
3986 // some files to take minutes to get rejected by the parser.
3987 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003988 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003989 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003990 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003991
Douglas Gregor01798682012-03-26 16:54:18 +00003992 // Determine whether we are going to search in the various namespaces for
3993 // corrections.
3994 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00003995 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00003996 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003997 // In a few cases we *only* want to search for corrections bases on just
3998 // adding or changing the nested name specifier.
3999 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00004000
4001 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004002 // For unqualified lookup, look through all of the names that we have
4003 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004004 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004005 for (IdentifierTable::iterator I = Context.Idents.begin(),
4006 IEnd = Context.Idents.end();
4007 I != IEnd; ++I)
4008 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004009
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004010 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004011 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004012 if (IdentifierInfoLookup *External
4013 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00004014 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004015 do {
4016 StringRef Name = Iter->Next();
4017 if (Name.empty())
4018 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00004019
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004020 Consumer.FoundName(Name);
4021 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00004022 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004023 }
4024
Richard Smith0f4b5be2012-06-08 21:35:42 +00004025 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004026
Douglas Gregoraaf87162010-04-14 20:04:41 +00004027 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004028 if (Consumer.empty()) {
4029 // If this was an unqualified lookup, note that no correction was found.
4030 if (IsUnqualifiedLookup)
4031 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004032
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004033 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004034 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004035
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004036 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4037 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004038 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004039 if (ED > 0 && Typo->getName().size() / ED < 3) {
4040 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00004041 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004042 (void)UnqualifiedTyposCorrected[Typo];
4043
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004044 return TypoCorrection();
4045 }
4046
Douglas Gregor01798682012-03-26 16:54:18 +00004047 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4048 // to search those namespaces.
4049 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004050 // Load any externally-known namespaces.
4051 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004052 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004053 LoadedExternalKnownNamespaces = true;
4054 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4055 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4056 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4057 }
4058
Nick Lewycky01a41142013-01-26 00:35:08 +00004059 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004060 KNI = KnownNamespaces.begin(),
4061 KNIEnd = KnownNamespaces.end();
4062 KNI != KNIEnd; ++KNI)
4063 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004064 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004065
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004066 // Weed out any names that could not be found by name lookup or, if a
4067 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004068 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004069 LookupResult TmpRes(*this, TypoName, LookupKind);
4070 TmpRes.suppressDiagnostics();
4071 while (!Consumer.empty()) {
4072 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
4073 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004074 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4075 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004076 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004077 // If we only want nested name specifier corrections, ignore potential
4078 // corrections that have a different base identifier from the typo.
4079 if (AllowOnlyNNSChanges &&
4080 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4081 TypoCorrectionConsumer::result_iterator Prev = I;
4082 ++I;
4083 DI->second.erase(Prev);
4084 continue;
4085 }
4086
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004087 // If the item already has been looked up or is a keyword, keep it.
4088 // If a validator callback object was given, drop the correction
4089 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004090 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00004091 for (TypoResultList::iterator RI = I->second.begin();
4092 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004093 TypoResultList::iterator Prev = RI;
4094 ++RI;
4095 if (Prev->isResolved()) {
4096 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00004097 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004098 else
4099 Viable = true;
4100 }
4101 }
4102 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004103 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004104 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004105 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004106 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004107 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00004108 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004109 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004110
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004111 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004112 TypoCorrection &Candidate = I->second.front();
4113 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004114 DeclContext *TempMemberContext = MemberContext;
4115 CXXScopeSpec *TempSS = SS;
4116retry_lookup:
4117 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4118 TempMemberContext, EnteringContext,
4119 CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004120
4121 switch (TmpRes.getResultKind()) {
4122 case LookupResult::NotFound:
4123 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004124 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004125 if (TempSS) {
4126 // Immediately retry the lookup without the given CXXScopeSpec
4127 TempSS = NULL;
4128 Candidate.WillReplaceSpecifier(true);
4129 goto retry_lookup;
4130 }
4131 if (TempMemberContext) {
4132 if (SS && !TempSS)
4133 TempSS = SS;
4134 TempMemberContext = NULL;
4135 goto retry_lookup;
4136 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004137 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004138 // We didn't find this name in our scope, or didn't like what we found;
4139 // ignore it.
4140 {
4141 TypoCorrectionConsumer::result_iterator Next = I;
4142 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004143 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004144 I = Next;
4145 }
4146 break;
4147
4148 case LookupResult::Ambiguous:
4149 // We don't deal with ambiguities.
4150 return TypoCorrection();
4151
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004152 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004153 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004154 // Store all of the Decls for overloaded symbols
4155 for (LookupResult::iterator TRD = TmpRes.begin(),
4156 TRDEnd = TmpRes.end();
4157 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004158 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004159 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004160 if (!isCandidateViable(CCC, Candidate)) {
4161 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004162 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004163 }
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004164 break;
4165 }
4166
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004167 case LookupResult::Found: {
4168 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004169 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004170 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004171 if (!isCandidateViable(CCC, Candidate)) {
4172 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004173 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004174 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004175 break;
4176 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004177
4178 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004180
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004181 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004182 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00004183 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004184 // If there are results in the closest possible bucket, stop
4185 break;
4186
4187 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004188 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004189 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004190 for (SmallVector<TypoCorrection,
4191 16>::iterator QRI = QualifiedResults.begin(),
4192 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004193 QRI != QRIEnd; ++QRI) {
4194 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4195 NIEnd = Namespaces.end();
4196 NI != NIEnd; ++NI) {
4197 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004198
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004199 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004200 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004201 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004202
4203 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004204 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004205 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4206
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004207 // Any corrections added below will be validated in subsequent
4208 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004209 switch (TmpRes.getResultKind()) {
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004210 case LookupResult::Found:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004211 case LookupResult::FoundOverloaded: {
4212 TypoCorrection TC(*QRI);
4213 TC.setCorrectionSpecifier(NI->NameSpecifier);
4214 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004215 TC.setCallbackDistance(0); // Reset the callback distance
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004216 for (LookupResult::iterator TRD = TmpRes.begin(),
4217 TRDEnd = TmpRes.end();
4218 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004219 TC.addCorrectionDecl(*TRD);
4220 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004221 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004222 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004223 case LookupResult::NotFound:
4224 case LookupResult::NotFoundInCurrentInstantiation:
4225 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004226 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004227 break;
4228 }
4229 }
4230 }
4231 }
4232
4233 QualifiedResults.clear();
4234 }
4235
4236 // No corrections remain...
4237 if (Consumer.empty()) return TypoCorrection();
4238
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004239 TypoResultsMap &BestResults = Consumer.getBestResults();
4240 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004241
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004242 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004243 // If this was an unqualified lookup and we believe the callback
4244 // object wouldn't have filtered out possible corrections, note
4245 // that no correction was found.
4246 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004247 (void)UnqualifiedTyposCorrected[Typo];
4248
4249 return TypoCorrection();
4250 }
4251
Douglas Gregore24b5752010-10-14 20:34:08 +00004252 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004253 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004254 const TypoResultList &CorrectionList = BestResults.begin()->second;
4255 const TypoCorrection &Result = CorrectionList.front();
4256 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004257
Douglas Gregor53e4b552010-10-26 17:18:00 +00004258 // Don't correct to a keyword that's the same as the typo; the keyword
4259 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004260 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4261
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004262 // Record the correction for unqualified lookup.
4263 if (IsUnqualifiedLookup)
4264 UnqualifiedTyposCorrected[Typo] = Result;
4265
David Blaikie6952c012012-10-12 20:00:44 +00004266 TypoCorrection TC = Result;
4267 TC.setCorrectionRange(SS, TypoName);
4268 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004269 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004270 else if (BestResults.size() > 1
4271 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4272 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4273 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4274 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004275 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004276 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004277 // Prefer 'super' when we're completing in a message-receiver
4278 // context.
4279
4280 // Don't correct to a keyword that's the same as the typo; the keyword
4281 // wasn't actually in scope.
4282 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004283
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004284 // Record the correction for unqualified lookup.
4285 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004286 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004287
David Blaikie6952c012012-10-12 20:00:44 +00004288 TypoCorrection TC = BestResults["super"].front();
4289 TC.setCorrectionRange(SS, TypoName);
4290 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004291 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004293 // If this was an unqualified lookup and we believe the callback object did
4294 // not filter out possible corrections, note that no correction was found.
4295 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004296 (void)UnqualifiedTyposCorrected[Typo];
4297
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004298 return TypoCorrection();
4299}
4300
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004301void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4302 if (!CDecl) return;
4303
4304 if (isKeyword())
4305 CorrectionDecls.clear();
4306
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004307 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004308
4309 if (!CorrectionName)
4310 CorrectionName = CDecl->getDeclName();
4311}
4312
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004313std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4314 if (CorrectionNameSpec) {
4315 std::string tmpBuffer;
4316 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4317 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikie17828ca2013-05-14 21:04:00 +00004318 PrefixOStream << CorrectionName;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004319 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004320 }
4321
4322 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004323}
Kaelyn Uhrain20a7cf42013-04-03 16:59:49 +00004324
4325bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4326 if (!candidate.isResolved())
4327 return true;
4328
4329 if (candidate.isKeyword())
4330 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4331 WantRemainingKeywords || WantObjCSuper;
4332
4333 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4334 CDeclEnd = candidate.end();
4335 CDecl != CDeclEnd; ++CDecl) {
4336 if (!isa<TypeDecl>(*CDecl))
4337 return true;
4338 }
4339
4340 return WantTypeSpecifiers;
4341}
Kaelyn Uhrain761695f2013-07-08 23:13:39 +00004342
4343FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4344 bool HasExplicitTemplateArgs)
4345 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
4346 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4347 WantRemainingKeywords = false;
4348}
4349
4350bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4351 if (!candidate.getCorrectionDecl())
4352 return candidate.isKeyword();
4353
4354 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4355 DIEnd = candidate.end();
4356 DI != DIEnd; ++DI) {
4357 FunctionDecl *FD = 0;
4358 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4359 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4360 FD = FTD->getTemplatedDecl();
4361 if (!HasExplicitTemplateArgs && !FD) {
4362 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4363 // If the Decl is neither a function nor a template function,
4364 // determine if it is a pointer or reference to a function. If so,
4365 // check against the number of arguments expected for the pointee.
4366 QualType ValType = cast<ValueDecl>(ND)->getType();
4367 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4368 ValType = ValType->getPointeeType();
4369 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4370 if (FPT->getNumArgs() == NumArgs)
4371 return true;
4372 }
4373 }
4374 if (FD && FD->getNumParams() >= NumArgs &&
4375 FD->getMinRequiredArguments() <= NumArgs)
4376 return true;
4377 }
4378 return false;
4379}
Richard Smith2d670972013-08-17 00:46:16 +00004380
4381void Sema::diagnoseTypo(const TypoCorrection &Correction,
4382 const PartialDiagnostic &TypoDiag,
4383 bool ErrorRecovery) {
4384 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4385 ErrorRecovery);
4386}
4387
4388/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4389/// itself to allow external validation of the result, etc.
4390///
4391/// \param Correction The result of performing typo correction.
4392/// \param TypoDiag The diagnostic to produce. This will have the corrected
4393/// string added to it (and usually also a fixit).
4394/// \param PrevNote A note to use when indicating the location of the entity to
4395/// which we are correcting. Will have the correction string added to it.
4396/// \param ErrorRecovery If \c true (the default), the caller is going to
4397/// recover from the typo as if the corrected string had been typed.
4398/// In this case, \c PDiag must be an error, and we will attach a fixit
4399/// to it.
4400void Sema::diagnoseTypo(const TypoCorrection &Correction,
4401 const PartialDiagnostic &TypoDiag,
4402 const PartialDiagnostic &PrevNote,
4403 bool ErrorRecovery) {
4404 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4405 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4406 FixItHint FixTypo = FixItHint::CreateReplacement(
4407 Correction.getCorrectionRange(), CorrectedStr);
4408
4409 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4410 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4411
4412 NamedDecl *ChosenDecl =
4413 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4414 if (PrevNote.getDiagID() && ChosenDecl)
4415 Diag(ChosenDecl->getLocation(), PrevNote)
4416 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4417}