blob: d0bb9f6abe6c29a8bc25939b6cb7dbd18360b49e [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();
855
Douglas Gregora376d102010-07-02 21:50:04 +0000856 // If this is the name of an implicitly-declared special member function,
857 // go through the scope stack to implicitly declare
858 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
859 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
860 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
861 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
862 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000863
Douglas Gregora376d102010-07-02 21:50:04 +0000864 // Implicitly declare member functions with the name we're looking for, if in
865 // fact we are in a scope where it matters.
866
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000867 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000868 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000869 I = IdResolver.begin(Name),
870 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000871
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000872 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000873 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000874 // ...During unqualified name lookup (3.4.1), the names appear as if
875 // they were declared in the nearest enclosing namespace which contains
876 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000877 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000878 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000879 //
880 // For example:
881 // namespace A { int i; }
882 // void foo() {
883 // int i;
884 // {
885 // using namespace A;
886 // ++i; // finds local 'i', A::i appears at global scope
887 // }
888 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000889 //
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000890 UnqualUsingDirectiveSet UDirs;
891 bool VisitedUsingDirectives = false;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000892 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000893 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000894 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
895
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000896 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000897 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000898 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000899 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000900 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000901 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000902 }
903 }
John McCallf36e02d2009-10-09 21:13:30 +0000904 if (Found) {
905 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000906 if (S->isClassScope())
907 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
908 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000909 return true;
910 }
911
Richard Smith4e9686b2013-08-09 04:35:01 +0000912 if (R.getLookupKind() == LookupLocalFriendName && !S->isClassScope()) {
913 // C++11 [class.friend]p11:
914 // If a friend declaration appears in a local class and the name
915 // specified is an unqualified name, a prior declaration is
916 // looked up without considering scopes that are outside the
917 // innermost enclosing non-class scope.
918 return false;
919 }
920
Douglas Gregor711be1e2010-03-15 14:33:29 +0000921 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
922 S->getParent() && !S->getParent()->isTemplateParamScope()) {
923 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000924 // found nothing, so look into the contexts between the
Douglas Gregor711be1e2010-03-15 14:33:29 +0000925 // lexical and semantic declaration contexts returned by
926 // findOuterContext(). This implements the name lookup behavior
927 // of C++ [temp.local]p8.
928 Ctx = OutsideOfTemplateParamDC;
929 OutsideOfTemplateParamDC = 0;
930 }
931
932 if (Ctx) {
933 DeclContext *OuterCtx;
934 bool SearchAfterTemplateScope;
935 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
936 if (SearchAfterTemplateScope)
937 OutsideOfTemplateParamDC = OuterCtx;
938
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000939 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000940 // We do not directly look into transparent contexts, since
941 // those entities will be found in the nearest enclosing
942 // non-transparent context.
943 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000944 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000945
946 // We do not look directly into function or method contexts,
947 // since all of the local variables and parameters of the
948 // function/method are present within the Scope.
949 if (Ctx->isFunctionOrMethod()) {
950 // If we have an Objective-C instance method, look for ivars
951 // in the corresponding interface.
952 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
953 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
954 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
955 ObjCInterfaceDecl *ClassDeclared;
956 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000957 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000958 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000959 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
960 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000961 R.resolveKind();
962 return true;
963 }
964 }
965 }
966 }
967
968 continue;
969 }
970
Douglas Gregor6bed88e2013-03-27 12:51:49 +0000971 // If this is a file context, we need to perform unqualified name
972 // lookup considering using directives.
973 if (Ctx->isFileContext()) {
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000974 // If we haven't handled using directives yet, do so now.
975 if (!VisitedUsingDirectives) {
976 // Add using directives from this context up to the top level.
Douglas Gregor34366202013-04-09 01:49:26 +0000977 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
978 if (UCtx->isTransparentContext())
979 continue;
980
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000981 UDirs.visit(UCtx, UCtx);
Douglas Gregor34366202013-04-09 01:49:26 +0000982 }
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000983
984 // Find the innermost file scope, so we can add using directives
985 // from local scopes.
986 Scope *InnermostFileScope = S;
987 while (InnermostFileScope &&
988 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
989 InnermostFileScope = InnermostFileScope->getParent();
990 UDirs.visitScopeChain(Initial, InnermostFileScope);
991
992 UDirs.done();
993
994 VisitedUsingDirectives = true;
995 }
Douglas Gregor6bed88e2013-03-27 12:51:49 +0000996
997 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
998 R.resolveKind();
999 return true;
1000 }
1001
1002 continue;
1003 }
1004
Douglas Gregore942bbe2009-09-10 16:57:35 +00001005 // Perform qualified name lookup into this context.
1006 // FIXME: In some cases, we know that every name that could be found by
1007 // this qualified name lookup will also be on the identifier chain. For
1008 // example, inside a class without any base classes, we never need to
1009 // perform qualified lookup because all of the members are on top of the
1010 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001011 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +00001012 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +00001013 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001014 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001015 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001016
John McCalld7be78a2009-11-10 07:01:13 +00001017 // Stop if we ran out of scopes.
1018 // FIXME: This really, really shouldn't be happening.
1019 if (!S) return false;
1020
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001021 // If we are looking for members, no need to look into global/namespace scope.
1022 if (R.getLookupKind() == LookupMemberName)
1023 return false;
1024
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001025 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001026 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +00001027 //
Mike Stump390b4cc2009-05-16 07:39:55 +00001028 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1029 // don't build it for each lookup!
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001030 if (!VisitedUsingDirectives) {
1031 UDirs.visitScopeChain(Initial, S);
1032 UDirs.done();
1033 }
1034
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001035 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001036 // Unqualified name lookup in C++ requires looking into scopes
1037 // that aren't strictly lexical, and therefore we walk through the
1038 // context as well as walking through the scopes.
1039 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001040 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +00001041 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +00001042 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +00001043 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001044 // We found something. Look for anything else in our scope
1045 // with this same name and in an acceptable identifier
1046 // namespace, so that we can construct an overload set if we
1047 // need to.
John McCallf36e02d2009-10-09 21:13:30 +00001048 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +00001049 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001050 }
1051 }
1052
Douglas Gregor00b4b032010-05-14 04:53:42 +00001053 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +00001054 R.resolveKind();
1055 return true;
1056 }
1057
Douglas Gregor00b4b032010-05-14 04:53:42 +00001058 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1059 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1060 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1061 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001062 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001063 // lexical and semantic declaration contexts returned by
1064 // findOuterContext(). This implements the name lookup behavior
1065 // of C++ [temp.local]p8.
1066 Ctx = OutsideOfTemplateParamDC;
1067 OutsideOfTemplateParamDC = 0;
1068 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001069
Douglas Gregor00b4b032010-05-14 04:53:42 +00001070 if (Ctx) {
1071 DeclContext *OuterCtx;
1072 bool SearchAfterTemplateScope;
1073 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1074 if (SearchAfterTemplateScope)
1075 OutsideOfTemplateParamDC = OuterCtx;
1076
1077 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1078 // We do not directly look into transparent contexts, since
1079 // those entities will be found in the nearest enclosing
1080 // non-transparent context.
1081 if (Ctx->isTransparentContext())
1082 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001083
Douglas Gregor00b4b032010-05-14 04:53:42 +00001084 // If we have a context, and it's not a context stashed in the
1085 // template parameter scope for an out-of-line definition, also
1086 // look into that context.
1087 if (!(Found && S && S->isTemplateParamScope())) {
1088 assert(Ctx->isFileContext() &&
1089 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001090
Douglas Gregor00b4b032010-05-14 04:53:42 +00001091 // Look into context considering using-directives.
1092 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1093 Found = true;
1094 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001095
Douglas Gregor00b4b032010-05-14 04:53:42 +00001096 if (Found) {
1097 R.resolveKind();
1098 return true;
1099 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001100
Douglas Gregor00b4b032010-05-14 04:53:42 +00001101 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1102 return false;
1103 }
1104 }
1105
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001106 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001107 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001108 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001109
John McCallf36e02d2009-10-09 21:13:30 +00001110 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001111}
1112
Richard Smithb7751002013-07-25 23:08:39 +00001113/// \brief Find the declaration that a class temploid member specialization was
1114/// instantiated from, or the member itself if it is an explicit specialization.
1115static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1116 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1117}
1118
1119/// \brief Find the module in which the given declaration was defined.
1120static Module *getDefiningModule(Decl *Entity) {
1121 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1122 // If this function was instantiated from a template, the defining module is
1123 // the module containing the pattern.
1124 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1125 Entity = Pattern;
1126 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1127 // If it's a class template specialization, find the template or partial
1128 // specialization from which it was instantiated.
1129 if (ClassTemplateSpecializationDecl *SpecRD =
1130 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1131 llvm::PointerUnion<ClassTemplateDecl*,
1132 ClassTemplatePartialSpecializationDecl*> From =
1133 SpecRD->getInstantiatedFrom();
1134 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1135 Entity = FromTemplate->getTemplatedDecl();
1136 else if (From)
1137 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1138 // Otherwise, it's an explicit specialization.
1139 } else if (MemberSpecializationInfo *MSInfo =
1140 RD->getMemberSpecializationInfo())
1141 Entity = getInstantiatedFrom(RD, MSInfo);
1142 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1143 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1144 Entity = getInstantiatedFrom(ED, MSInfo);
1145 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1146 // FIXME: Map from variable template specializations back to the template.
1147 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1148 Entity = getInstantiatedFrom(VD, MSInfo);
1149 }
1150
1151 // Walk up to the containing context. That might also have been instantiated
1152 // from a template.
1153 DeclContext *Context = Entity->getDeclContext();
1154 if (Context->isFileContext())
1155 return Entity->getOwningModule();
1156 return getDefiningModule(cast<Decl>(Context));
1157}
1158
1159llvm::DenseSet<Module*> &Sema::getLookupModules() {
1160 unsigned N = ActiveTemplateInstantiations.size();
1161 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1162 I != N; ++I) {
1163 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1164 if (M && !LookupModulesCache.insert(M).second)
1165 M = 0;
1166 ActiveTemplateInstantiationLookupModules.push_back(M);
1167 }
1168 return LookupModulesCache;
1169}
1170
1171/// \brief Determine whether a declaration is visible to name lookup.
1172///
1173/// This routine determines whether the declaration D is visible in the current
1174/// lookup context, taking into account the current template instantiation
1175/// stack. During template instantiation, a declaration is visible if it is
1176/// visible from a module containing any entity on the template instantiation
1177/// path (by instantiating a template, you allow it to see the declarations that
1178/// your module can see, including those later on in your module).
1179bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1180 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1181 "should not call this: not in slow case");
1182 Module *DeclModule = D->getOwningModule();
1183 assert(DeclModule && "hidden decl not from a module");
1184
1185 // Find the extra places where we need to look.
1186 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1187 if (LookupModules.empty())
1188 return false;
1189
1190 // If our lookup set contains the decl's module, it's visible.
1191 if (LookupModules.count(DeclModule))
1192 return true;
1193
1194 // If the declaration isn't exported, it's not visible in any other module.
1195 if (D->isModulePrivate())
1196 return false;
1197
1198 // Check whether DeclModule is transitively exported to an import of
1199 // the lookup set.
1200 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1201 E = LookupModules.end();
1202 I != E; ++I)
1203 if ((*I)->isModuleVisible(DeclModule))
1204 return true;
1205 return false;
1206}
1207
Douglas Gregor55368912011-12-14 16:03:29 +00001208/// \brief Retrieve the visible declaration corresponding to D, if any.
1209///
1210/// This routine determines whether the declaration D is visible in the current
1211/// module, with the current imports. If not, it checks whether any
1212/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smithb7751002013-07-25 23:08:39 +00001213///
Douglas Gregor55368912011-12-14 16:03:29 +00001214/// \returns D, or a visible previous declaration of D, whichever is more recent
1215/// and visible. If no declaration of D is visible, returns null.
Richard Smithb7751002013-07-25 23:08:39 +00001216NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1217 assert(!isVisible(SemaRef, D) && "not in slow case");
1218
Douglas Gregor0782ef22012-01-06 22:05:37 +00001219 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1220 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001221 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Richard Smithb7751002013-07-25 23:08:39 +00001222 if (isVisible(SemaRef, ND))
Douglas Gregor0782ef22012-01-06 22:05:37 +00001223 return ND;
1224 }
Douglas Gregor55368912011-12-14 16:03:29 +00001225 }
Richard Smithb7751002013-07-25 23:08:39 +00001226
Douglas Gregor55368912011-12-14 16:03:29 +00001227 return 0;
1228}
1229
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001230/// @brief Perform unqualified name lookup starting from a given
1231/// scope.
1232///
1233/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1234/// used to find names within the current scope. For example, 'x' in
1235/// @code
1236/// int x;
1237/// int f() {
1238/// return x; // unqualified name look finds 'x' in the global scope
1239/// }
1240/// @endcode
1241///
1242/// Different lookup criteria can find different names. For example, a
1243/// particular scope can have both a struct and a function of the same
1244/// name, and each can be found by certain lookup criteria. For more
1245/// information about lookup criteria, see the documentation for the
1246/// class LookupCriteria.
1247///
1248/// @param S The scope from which unqualified name lookup will
1249/// begin. If the lookup criteria permits, name lookup may also search
1250/// in the parent scopes.
1251///
James Dennett8da16872012-06-22 10:32:46 +00001252/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1253/// look up and the lookup kind), and is updated with the results of lookup
1254/// including zero or more declarations and possibly additional information
1255/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001256///
James Dennett8da16872012-06-22 10:32:46 +00001257/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001258bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1259 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001260 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001261
John McCalla24dc2e2009-11-17 02:14:36 +00001262 LookupNameKind NameKind = R.getLookupKind();
1263
David Blaikie4e4d0842012-03-11 07:00:24 +00001264 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001265 // Unqualified name lookup in C/Objective-C is purely lexical, so
1266 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001267 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001268 // Find the nearest non-transparent declaration scope.
1269 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001270 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001271 static_cast<DeclContext *>(S->getEntity())
1272 ->isTransparentContext()))
1273 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001274 }
1275
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001276 // Scan up the scope chain looking for a decl that matches this
1277 // identifier that is in the appropriate namespace. This search
1278 // should not take long, as shadowing of names is uncommon, and
1279 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001280 bool LeftStartingScope = false;
1281
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001282 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001283 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001284 I != IEnd; ++I)
Richard Smithb7751002013-07-25 23:08:39 +00001285 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001286 if (NameKind == LookupRedeclarationWithLinkage) {
1287 // Determine whether this (or a previous) declaration is
1288 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001289 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001290 LeftStartingScope = true;
1291
1292 // If we found something outside of our starting scope that
1293 // does not have linkage, skip it.
1294 if (LeftStartingScope && !((*I)->hasLinkage()))
1295 continue;
1296 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001297 else if (NameKind == LookupObjCImplicitSelfParam &&
1298 !isa<ImplicitParamDecl>(*I))
1299 continue;
Richard Smithb7751002013-07-25 23:08:39 +00001300
Douglas Gregor55368912011-12-14 16:03:29 +00001301 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001302
Douglas Gregor7a537402012-01-03 23:26:26 +00001303 // Check whether there are any other declarations with the same name
1304 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001305 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001306 // Find the scope in which this declaration was declared (if it
1307 // actually exists in a Scope).
1308 while (S && !S->isDeclScope(D))
1309 S = S->getParent();
1310
1311 // If the scope containing the declaration is the translation unit,
1312 // then we'll need to perform our checks based on the matching
1313 // DeclContexts rather than matching scopes.
1314 if (S && isNamespaceOrTranslationUnitScope(S))
1315 S = 0;
1316
1317 // Compute the DeclContext, if we need it.
1318 DeclContext *DC = 0;
1319 if (!S)
1320 DC = (*I)->getDeclContext()->getRedeclContext();
1321
Douglas Gregorda795b42012-01-04 16:44:10 +00001322 IdentifierResolver::iterator LastI = I;
1323 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001324 if (S) {
1325 // Match based on scope.
1326 if (!S->isDeclScope(*LastI))
1327 break;
1328 } else {
1329 // Match based on DeclContext.
1330 DeclContext *LastDC
1331 = (*LastI)->getDeclContext()->getRedeclContext();
1332 if (!LastDC->Equals(DC))
1333 break;
1334 }
Richard Smithb7751002013-07-25 23:08:39 +00001335
1336 // If the declaration is in the right namespace and visible, add it.
1337 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1338 R.addDecl(LastD);
Douglas Gregorda795b42012-01-04 16:44:10 +00001339 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001340
Douglas Gregorda795b42012-01-04 16:44:10 +00001341 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001342 }
John McCallf36e02d2009-10-09 21:13:30 +00001343 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001344 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001345 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001346 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001347 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001348 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001349 }
1350
1351 // If we didn't find a use of this identifier, and if the identifier
1352 // corresponds to a compiler builtin, create the decl object for the builtin
1353 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001354 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1355 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001356
Axel Naumannf8291a12011-02-24 16:47:47 +00001357 // If we didn't find a use of this identifier, the ExternalSource
1358 // may be able to handle the situation.
1359 // Note: some lookup failures are expected!
1360 // See e.g. R.isForRedeclaration().
1361 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001362}
1363
John McCall6e247262009-10-10 05:48:19 +00001364/// @brief Perform qualified name lookup in the namespaces nominated by
1365/// using directives by the given context.
1366///
1367/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001368/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001369/// (where X is the global namespace), let S be the set of all
1370/// declarations of m in X and in the transitive closure of all
1371/// namespaces nominated by using-directives in X and its used
1372/// namespaces, except that using-directives are ignored in any
1373/// namespace, including X, directly containing one or more
1374/// declarations of m. No namespace is searched more than once in
1375/// the lookup of a name. If S is the empty set, the program is
1376/// ill-formed. Otherwise, if S has exactly one member, or if the
1377/// context of the reference is a using-declaration
1378/// (namespace.udecl), S is the required set of declarations of
1379/// m. Otherwise if the use of m is not one that allows a unique
1380/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001381///
John McCall6e247262009-10-10 05:48:19 +00001382/// C++98 [namespace.qual]p5:
1383/// During the lookup of a qualified namespace member name, if the
1384/// lookup finds more than one declaration of the member, and if one
1385/// declaration introduces a class name or enumeration name and the
1386/// other declarations either introduce the same object, the same
1387/// enumerator or a set of functions, the non-type name hides the
1388/// class or enumeration name if and only if the declarations are
1389/// from the same namespace; otherwise (the declarations are from
1390/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001391static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001392 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001393 assert(StartDC->isFileContext() && "start context is not a file context");
1394
1395 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1396 DeclContext::udir_iterator E = StartDC->using_directives_end();
1397
1398 if (I == E) return false;
1399
1400 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001401 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001402 Visited.insert(StartDC);
1403
1404 // We have not yet looked into these namespaces, much less added
1405 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001406 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001407
1408 // We have already looked into the initial namespace; seed the queue
1409 // with its using-children.
1410 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001411 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001412 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001413 Queue.push_back(ND);
1414 }
1415
1416 // The easiest way to implement the restriction in [namespace.qual]p5
1417 // is to check whether any of the individual results found a tag
1418 // and, if so, to declare an ambiguity if the final result is not
1419 // a tag.
1420 bool FoundTag = false;
1421 bool FoundNonTag = false;
1422
John McCall7d384dd2009-11-18 07:57:50 +00001423 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001424
1425 bool Found = false;
1426 while (!Queue.empty()) {
1427 NamespaceDecl *ND = Queue.back();
1428 Queue.pop_back();
1429
1430 // We go through some convolutions here to avoid copying results
1431 // between LookupResults.
1432 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001433 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001434 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001435
1436 if (FoundDirect) {
1437 // First do any local hiding.
1438 DirectR.resolveKind();
1439
1440 // If the local result is a tag, remember that.
1441 if (DirectR.isSingleTagDecl())
1442 FoundTag = true;
1443 else
1444 FoundNonTag = true;
1445
1446 // Append the local results to the total results if necessary.
1447 if (UseLocal) {
1448 R.addAllDecls(LocalR);
1449 LocalR.clear();
1450 }
1451 }
1452
1453 // If we find names in this namespace, ignore its using directives.
1454 if (FoundDirect) {
1455 Found = true;
1456 continue;
1457 }
1458
1459 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1460 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001461 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001462 Queue.push_back(Nom);
1463 }
1464 }
1465
1466 if (Found) {
1467 if (FoundTag && FoundNonTag)
1468 R.setAmbiguousQualifiedTagHiding();
1469 else
1470 R.resolveKind();
1471 }
1472
1473 return Found;
1474}
1475
Douglas Gregor8071e422010-08-15 06:18:01 +00001476/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001477static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001478 CXXBasePath &Path,
1479 void *Name) {
1480 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001481
Douglas Gregor8071e422010-08-15 06:18:01 +00001482 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1483 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001484 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001485}
1486
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001487/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001488/// static members, nested types, and enumerators.
1489template<typename InputIterator>
1490static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1491 Decl *D = (*First)->getUnderlyingDecl();
1492 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1493 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001494
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001495 if (isa<CXXMethodDecl>(D)) {
1496 // Determine whether all of the methods are static.
1497 bool AllMethodsAreStatic = true;
1498 for(; First != Last; ++First) {
1499 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001500
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001501 if (!isa<CXXMethodDecl>(D)) {
1502 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1503 break;
1504 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001505
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001506 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1507 AllMethodsAreStatic = false;
1508 break;
1509 }
1510 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001511
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001512 if (AllMethodsAreStatic)
1513 return true;
1514 }
1515
1516 return false;
1517}
1518
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001519/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001520///
1521/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1522/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001523/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001524///
1525/// Different lookup criteria can find different names. For example, a
1526/// particular scope can have both a struct and a function of the same
1527/// name, and each can be found by certain lookup criteria. For more
1528/// information about lookup criteria, see the documentation for the
1529/// class LookupCriteria.
1530///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001531/// \param R captures both the lookup criteria and any lookup results found.
1532///
1533/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001534/// search. If the lookup criteria permits, name lookup may also search
1535/// in the parent contexts or (for C++ classes) base classes.
1536///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001537/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001538/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001539///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001540/// \returns true if lookup succeeded, false if it failed.
1541bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1542 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001543 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001544
John McCalla24dc2e2009-11-17 02:14:36 +00001545 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001546 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001548 // Make sure that the declaration context is complete.
1549 assert((!isa<TagDecl>(LookupCtx) ||
1550 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001551 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001552 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001553 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001555 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001556 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001557 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001558 if (isa<CXXRecordDecl>(LookupCtx))
1559 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001560 return true;
1561 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001562
John McCall6e247262009-10-10 05:48:19 +00001563 // Don't descend into implied contexts for redeclarations.
1564 // C++98 [namespace.qual]p6:
1565 // In a declaration for a namespace member in which the
1566 // declarator-id is a qualified-id, given that the qualified-id
1567 // for the namespace member has the form
1568 // nested-name-specifier unqualified-id
1569 // the unqualified-id shall name a member of the namespace
1570 // designated by the nested-name-specifier.
1571 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001572 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001573 return false;
1574
John McCalla24dc2e2009-11-17 02:14:36 +00001575 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001576 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001577 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001578
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001579 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001580 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001581 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001582 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001583 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001584
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001585 // If we're performing qualified name lookup into a dependent class,
1586 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001587 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001588 // template instantiation time (at which point all bases will be available)
1589 // or we have to fail.
1590 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1591 LookupRec->hasAnyDependentBases()) {
1592 R.setNotFoundInCurrentInstantiation();
1593 return false;
1594 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001595
Douglas Gregor7176fff2009-01-15 00:26:24 +00001596 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001597 CXXBasePaths Paths;
1598 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001599
1600 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001601 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001602 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001603 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001604 case LookupOrdinaryName:
1605 case LookupMemberName:
1606 case LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +00001607 case LookupLocalFriendName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001608 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1609 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001610
Douglas Gregora8f32e02009-10-06 17:59:45 +00001611 case LookupTagName:
1612 BaseCallback = &CXXRecordDecl::FindTagMember;
1613 break;
John McCall9f54ad42009-12-10 09:41:52 +00001614
Douglas Gregor8071e422010-08-15 06:18:01 +00001615 case LookupAnyName:
1616 BaseCallback = &LookupAnyMember;
1617 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001618
John McCall9f54ad42009-12-10 09:41:52 +00001619 case LookupUsingDeclName:
1620 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001621
Douglas Gregora8f32e02009-10-06 17:59:45 +00001622 case LookupOperatorName:
1623 case LookupNamespaceName:
1624 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001625 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001626 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001627 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001628
Douglas Gregora8f32e02009-10-06 17:59:45 +00001629 case LookupNestedNameSpecifierName:
1630 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1631 break;
1632 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633
John McCalla24dc2e2009-11-17 02:14:36 +00001634 if (!LookupRec->lookupInBases(BaseCallback,
1635 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001636 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001637
John McCall92f88312010-01-23 00:46:32 +00001638 R.setNamingClass(LookupRec);
1639
Douglas Gregor7176fff2009-01-15 00:26:24 +00001640 // C++ [class.member.lookup]p2:
1641 // [...] If the resulting set of declarations are not all from
1642 // sub-objects of the same type, or the set has a nonstatic member
1643 // and includes members from distinct sub-objects, there is an
1644 // ambiguity and the program is ill-formed. Otherwise that set is
1645 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001646 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001647 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001648 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001649
Douglas Gregora8f32e02009-10-06 17:59:45 +00001650 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001651 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001652 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001653
John McCall46460a62010-01-20 21:53:11 +00001654 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1655 // across all paths.
1656 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001657
Douglas Gregor7176fff2009-01-15 00:26:24 +00001658 // Determine whether we're looking at a distinct sub-object or not.
1659 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001660 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001661 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1662 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001663 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001664 }
1665
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001666 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001667 != Context.getCanonicalType(PathElement.Base->getType())) {
1668 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001669 // different types. If the declaration sets aren't the same, this
1670 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001671 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001672 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001673 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1674 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001675
David Blaikie3bc93e32012-12-19 00:45:41 +00001676 while (FirstD != FirstPath->Decls.end() &&
1677 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001678 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1679 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1680 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001681
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001682 ++FirstD;
1683 ++CurrentD;
1684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001685
David Blaikie3bc93e32012-12-19 00:45:41 +00001686 if (FirstD == FirstPath->Decls.end() &&
1687 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001688 continue;
1689 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001690
John McCallf36e02d2009-10-09 21:13:30 +00001691 R.setAmbiguousBaseSubobjectTypes(Paths);
1692 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001693 }
1694
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001695 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001696 // We have a different subobject of the same type.
1697
1698 // C++ [class.member.lookup]p5:
1699 // A static member, a nested type or an enumerator defined in
1700 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001701 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001702 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001703 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704
Douglas Gregor7176fff2009-01-15 00:26:24 +00001705 // We have found a nonstatic member name in multiple, distinct
1706 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001707 R.setAmbiguousBaseSubobjects(Paths);
1708 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001709 }
1710 }
1711
1712 // Lookup in a base class succeeded; return these results.
1713
David Blaikie3bc93e32012-12-19 00:45:41 +00001714 DeclContext::lookup_result DR = Paths.front().Decls;
1715 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001716 NamedDecl *D = *I;
1717 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1718 D->getAccess());
1719 R.addDecl(D, AS);
1720 }
John McCallf36e02d2009-10-09 21:13:30 +00001721 R.resolveKind();
1722 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001723}
1724
1725/// @brief Performs name lookup for a name that was parsed in the
1726/// source code, and may contain a C++ scope specifier.
1727///
1728/// This routine is a convenience routine meant to be called from
1729/// contexts that receive a name and an optional C++ scope specifier
1730/// (e.g., "N::M::x"). It will then perform either qualified or
1731/// unqualified name lookup (with LookupQualifiedName or LookupName,
1732/// respectively) on the given name and return those results.
1733///
1734/// @param S The scope from which unqualified name lookup will
1735/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001736///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001737/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001738///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001739/// @param EnteringContext Indicates whether we are going to enter the
1740/// context of the scope-specifier SS (if present).
1741///
John McCallf36e02d2009-10-09 21:13:30 +00001742/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001743bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001744 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001745 if (SS && SS->isInvalid()) {
1746 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001747 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001748 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001749 }
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Douglas Gregor495c35d2009-08-25 22:51:20 +00001751 if (SS && SS->isSet()) {
1752 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001753 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001754 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001755 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001756 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001757
John McCalla24dc2e2009-11-17 02:14:36 +00001758 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001759 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001760 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001761
Douglas Gregor495c35d2009-08-25 22:51:20 +00001762 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001763 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001764 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001765 R.setNotFoundInCurrentInstantiation();
1766 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001767 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001768 }
1769
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001771 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001772}
1773
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001774
James Dennett16ae9de2012-06-22 10:16:05 +00001775/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001776/// from name lookup.
1777///
James Dennett16ae9de2012-06-22 10:16:05 +00001778/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump1eb44332009-09-09 15:08:12 +00001779///
James Dennett16ae9de2012-06-22 10:16:05 +00001780/// \returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001781bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001782 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1783
John McCalla24dc2e2009-11-17 02:14:36 +00001784 DeclarationName Name = Result.getLookupName();
1785 SourceLocation NameLoc = Result.getNameLoc();
1786 SourceRange LookupRange = Result.getContextRange();
1787
John McCall6e247262009-10-10 05:48:19 +00001788 switch (Result.getAmbiguityKind()) {
1789 case LookupResult::AmbiguousBaseSubobjects: {
1790 CXXBasePaths *Paths = Result.getBasePaths();
1791 QualType SubobjectType = Paths->front().back().Base->getType();
1792 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1793 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1794 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795
David Blaikie3bc93e32012-12-19 00:45:41 +00001796 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001797 while (isa<CXXMethodDecl>(*Found) &&
1798 cast<CXXMethodDecl>(*Found)->isStatic())
1799 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001800
John McCall6e247262009-10-10 05:48:19 +00001801 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001802
John McCall6e247262009-10-10 05:48:19 +00001803 return true;
1804 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001805
John McCall6e247262009-10-10 05:48:19 +00001806 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001807 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1808 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001809
John McCall6e247262009-10-10 05:48:19 +00001810 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001811 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001812 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1813 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001814 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001815 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001816 if (DeclsPrinted.insert(D).second)
1817 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1818 }
1819
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001820 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001821 }
1822
John McCall6e247262009-10-10 05:48:19 +00001823 case LookupResult::AmbiguousTagHiding: {
1824 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001825
John McCall6e247262009-10-10 05:48:19 +00001826 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1827
1828 LookupResult::iterator DI, DE = Result.end();
1829 for (DI = Result.begin(); DI != DE; ++DI)
1830 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1831 TagDecls.insert(TD);
1832 Diag(TD->getLocation(), diag::note_hidden_tag);
1833 }
1834
1835 for (DI = Result.begin(); DI != DE; ++DI)
1836 if (!isa<TagDecl>(*DI))
1837 Diag((*DI)->getLocation(), diag::note_hiding_object);
1838
1839 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001840 LookupResult::Filter F = Result.makeFilter();
1841 while (F.hasNext()) {
1842 if (TagDecls.count(F.next()))
1843 F.erase();
1844 }
1845 F.done();
John McCall6e247262009-10-10 05:48:19 +00001846
1847 return true;
1848 }
1849
1850 case LookupResult::AmbiguousReference: {
1851 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001852
John McCall6e247262009-10-10 05:48:19 +00001853 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1854 for (; DI != DE; ++DI)
1855 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001856
John McCall6e247262009-10-10 05:48:19 +00001857 return true;
1858 }
1859 }
1860
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001861 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001862}
Douglas Gregorfa047642009-02-04 00:32:51 +00001863
John McCallc7e04da2010-05-28 18:45:08 +00001864namespace {
1865 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001866 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001867 Sema::AssociatedNamespaceSet &Namespaces,
1868 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001869 : S(S), Namespaces(Namespaces), Classes(Classes),
1870 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001871 }
1872
1873 Sema &S;
1874 Sema::AssociatedNamespaceSet &Namespaces;
1875 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001876 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001877 };
1878}
1879
Mike Stump1eb44332009-09-09 15:08:12 +00001880static void
John McCallc7e04da2010-05-28 18:45:08 +00001881addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001882
Douglas Gregor54022952010-04-30 07:08:38 +00001883static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1884 DeclContext *Ctx) {
1885 // Add the associated namespace for this class.
1886
1887 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1888 // be a locally scoped record.
1889
Sebastian Redl410c4f22010-08-31 20:53:31 +00001890 // We skip out of inline namespaces. The innermost non-inline namespace
1891 // contains all names of all its nested inline namespaces anyway, so we can
1892 // replace the entire inline namespace tree with its root.
1893 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1894 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001895 Ctx = Ctx->getParent();
1896
John McCall6ff07852009-08-07 22:18:02 +00001897 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001898 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001899}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001900
Mike Stump1eb44332009-09-09 15:08:12 +00001901// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001902// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001903static void
John McCallc7e04da2010-05-28 18:45:08 +00001904addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1905 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001906 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001907 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001908 switch (Arg.getKind()) {
1909 case TemplateArgument::Null:
1910 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Douglas Gregor69be8d62009-07-08 07:51:57 +00001912 case TemplateArgument::Type:
1913 // [...] the namespaces and classes associated with the types of the
1914 // template arguments provided for template type parameters (excluding
1915 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001916 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001917 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001918
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001919 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001920 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001921 // [...] the namespaces in which any template template arguments are
1922 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001923 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001924 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001925 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001926 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001927 DeclContext *Ctx = ClassTemplate->getDeclContext();
1928 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001929 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001930 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001931 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001932 }
1933 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001934 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001935
Douglas Gregor788cd062009-11-11 01:00:40 +00001936 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001937 case TemplateArgument::Integral:
1938 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001939 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001940 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001941 // associated namespaces. ]
1942 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Douglas Gregor69be8d62009-07-08 07:51:57 +00001944 case TemplateArgument::Pack:
1945 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1946 PEnd = Arg.pack_end();
1947 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001948 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001949 break;
1950 }
1951}
1952
Douglas Gregorfa047642009-02-04 00:32:51 +00001953// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001954// argument-dependent lookup with an argument of class type
1955// (C++ [basic.lookup.koenig]p2).
1956static void
John McCallc7e04da2010-05-28 18:45:08 +00001957addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1958 CXXRecordDecl *Class) {
1959
1960 // Just silently ignore anything whose name is __va_list_tag.
1961 if (Class->getDeclName() == Result.S.VAListTagName)
1962 return;
1963
Douglas Gregorfa047642009-02-04 00:32:51 +00001964 // C++ [basic.lookup.koenig]p2:
1965 // [...]
1966 // -- If T is a class type (including unions), its associated
1967 // classes are: the class itself; the class of which it is a
1968 // member, if any; and its direct and indirect base
1969 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001970 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001971
1972 // Add the class of which it is a member, if any.
1973 DeclContext *Ctx = Class->getDeclContext();
1974 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001975 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001976 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001977 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Douglas Gregorfa047642009-02-04 00:32:51 +00001979 // Add the class itself. If we've already seen this class, we don't
1980 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001981 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001982 return;
1983
Mike Stump1eb44332009-09-09 15:08:12 +00001984 // -- If T is a template-id, its associated namespaces and classes are
1985 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001986 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001987 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001988 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001989 // namespaces in which any template template arguments are defined; and
1990 // the classes in which any member templates used as template template
1991 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001992 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001993 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001994 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1995 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1996 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001997 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001998 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001999 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Douglas Gregor69be8d62009-07-08 07:51:57 +00002001 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2002 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00002003 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002004 }
Mike Stump1eb44332009-09-09 15:08:12 +00002005
John McCall86ff3082010-02-04 22:26:26 +00002006 // Only recurse into base classes for complete types.
2007 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00002008 QualType type = Result.S.Context.getTypeDeclType(Class);
2009 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
2010 /*no diagnostic*/ 0))
2011 return;
John McCall86ff3082010-02-04 22:26:26 +00002012 }
2013
Douglas Gregorfa047642009-02-04 00:32:51 +00002014 // Add direct and indirect base classes along with their associated
2015 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002016 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00002017 Bases.push_back(Class);
2018 while (!Bases.empty()) {
2019 // Pop this class off the stack.
2020 Class = Bases.back();
2021 Bases.pop_back();
2022
2023 // Visit the base classes.
2024 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
2025 BaseEnd = Class->bases_end();
2026 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002027 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00002028 // In dependent contexts, we do ADL twice, and the first time around,
2029 // the base type might be a dependent TemplateSpecializationType, or a
2030 // TemplateTypeParmType. If that happens, simply ignore it.
2031 // FIXME: If we want to support export, we probably need to add the
2032 // namespace of the template in a TemplateSpecializationType, or even
2033 // the classes and namespaces of known non-dependent arguments.
2034 if (!BaseType)
2035 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002036 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002037 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002038 // Find the associated namespace for this base class.
2039 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00002040 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002041
2042 // Make sure we visit the bases of this base class.
2043 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2044 Bases.push_back(BaseDecl);
2045 }
2046 }
2047 }
2048}
2049
2050// \brief Add the associated classes and namespaces for
2051// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00002052// (C++ [basic.lookup.koenig]p2).
2053static void
John McCallc7e04da2010-05-28 18:45:08 +00002054addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002055 // C++ [basic.lookup.koenig]p2:
2056 //
2057 // For each argument type T in the function call, there is a set
2058 // of zero or more associated namespaces and a set of zero or more
2059 // associated classes to be considered. The sets of namespaces and
2060 // classes is determined entirely by the types of the function
2061 // arguments (and the namespace of any template template
2062 // argument). Typedef names and using-declarations used to specify
2063 // the types do not contribute to this set. The sets of namespaces
2064 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00002065
Chris Lattner5f9e2722011-07-23 10:55:15 +00002066 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00002067 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2068
Douglas Gregorfa047642009-02-04 00:32:51 +00002069 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00002070 switch (T->getTypeClass()) {
2071
2072#define TYPE(Class, Base)
2073#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2074#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2075#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2076#define ABSTRACT_TYPE(Class, Base)
2077#include "clang/AST/TypeNodes.def"
2078 // T is canonical. We can also ignore dependent types because
2079 // we don't need to do ADL at the definition point, but if we
2080 // wanted to implement template export (or if we find some other
2081 // use for associated classes and namespaces...) this would be
2082 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00002083 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002084
John McCallfa4edcf2010-05-28 06:08:54 +00002085 // -- If T is a pointer to U or an array of U, its associated
2086 // namespaces and classes are those associated with U.
2087 case Type::Pointer:
2088 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2089 continue;
2090 case Type::ConstantArray:
2091 case Type::IncompleteArray:
2092 case Type::VariableArray:
2093 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2094 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002095
John McCallfa4edcf2010-05-28 06:08:54 +00002096 // -- If T is a fundamental type, its associated sets of
2097 // namespaces and classes are both empty.
2098 case Type::Builtin:
2099 break;
2100
2101 // -- If T is a class type (including unions), its associated
2102 // classes are: the class itself; the class of which it is a
2103 // member, if any; and its direct and indirect base
2104 // classes. Its associated namespaces are the namespaces in
2105 // which its associated classes are defined.
2106 case Type::Record: {
2107 CXXRecordDecl *Class
2108 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002109 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00002110 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002111 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00002112
John McCallfa4edcf2010-05-28 06:08:54 +00002113 // -- If T is an enumeration type, its associated namespace is
2114 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002115 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00002116 // it has no associated class.
2117 case Type::Enum: {
2118 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002119
John McCallfa4edcf2010-05-28 06:08:54 +00002120 DeclContext *Ctx = Enum->getDeclContext();
2121 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002122 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002123
John McCallfa4edcf2010-05-28 06:08:54 +00002124 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002125 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002126
John McCallfa4edcf2010-05-28 06:08:54 +00002127 break;
2128 }
2129
2130 // -- If T is a function type, its associated namespaces and
2131 // classes are those associated with the function parameter
2132 // types and those associated with the return type.
2133 case Type::FunctionProto: {
2134 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2135 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2136 ArgEnd = Proto->arg_type_end();
2137 Arg != ArgEnd; ++Arg)
2138 Queue.push_back(Arg->getTypePtr());
2139 // fallthrough
2140 }
2141 case Type::FunctionNoProto: {
2142 const FunctionType *FnType = cast<FunctionType>(T);
2143 T = FnType->getResultType().getTypePtr();
2144 continue;
2145 }
2146
2147 // -- If T is a pointer to a member function of a class X, its
2148 // associated namespaces and classes are those associated
2149 // with the function parameter types and return type,
2150 // together with those associated with X.
2151 //
2152 // -- If T is a pointer to a data member of class X, its
2153 // associated namespaces and classes are those associated
2154 // with the member type together with those associated with
2155 // X.
2156 case Type::MemberPointer: {
2157 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2158
2159 // Queue up the class type into which this points.
2160 Queue.push_back(MemberPtr->getClass());
2161
2162 // And directly continue with the pointee type.
2163 T = MemberPtr->getPointeeType().getTypePtr();
2164 continue;
2165 }
2166
2167 // As an extension, treat this like a normal pointer.
2168 case Type::BlockPointer:
2169 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2170 continue;
2171
2172 // References aren't covered by the standard, but that's such an
2173 // obvious defect that we cover them anyway.
2174 case Type::LValueReference:
2175 case Type::RValueReference:
2176 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2177 continue;
2178
2179 // These are fundamental types.
2180 case Type::Vector:
2181 case Type::ExtVector:
2182 case Type::Complex:
2183 break;
2184
Richard Smithdc7a4f52013-04-30 13:56:41 +00002185 // Non-deduced auto types only get here for error cases.
2186 case Type::Auto:
2187 break;
2188
Douglas Gregorf25760e2011-04-12 01:02:45 +00002189 // If T is an Objective-C object or interface type, or a pointer to an
2190 // object or interface type, the associated namespace is the global
2191 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002192 case Type::ObjCObject:
2193 case Type::ObjCInterface:
2194 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002195 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002196 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002197
2198 // Atomic types are just wrappers; use the associations of the
2199 // contained type.
2200 case Type::Atomic:
2201 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2202 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002203 }
2204
2205 if (Queue.empty()) break;
2206 T = Queue.back();
2207 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002208 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002209}
2210
2211/// \brief Find the associated classes and namespaces for
2212/// argument-dependent lookup for a call with the given set of
2213/// arguments.
2214///
2215/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002216/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002217/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm834c0582013-08-09 18:02:13 +00002218void Sema::FindAssociatedClassesAndNamespaces(
2219 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2220 AssociatedNamespaceSet &AssociatedNamespaces,
2221 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002222 AssociatedNamespaces.clear();
2223 AssociatedClasses.clear();
2224
John McCall42f48fb2012-08-24 20:38:34 +00002225 AssociatedLookup Result(*this, InstantiationLoc,
2226 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002227
Douglas Gregorfa047642009-02-04 00:32:51 +00002228 // C++ [basic.lookup.koenig]p2:
2229 // For each argument type T in the function call, there is a set
2230 // of zero or more associated namespaces and a set of zero or more
2231 // associated classes to be considered. The sets of namespaces and
2232 // classes is determined entirely by the types of the function
2233 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002234 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002235 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002236 Expr *Arg = Args[ArgIdx];
2237
2238 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002239 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002240 continue;
2241 }
2242
2243 // [...] In addition, if the argument is the name or address of a
2244 // set of overloaded functions and/or function templates, its
2245 // associated classes and namespaces are the union of those
2246 // associated with each of the members of the set: the namespace
2247 // in which the function or function template is defined and the
2248 // classes and namespaces associated with its (non-dependent)
2249 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002250 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002251 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002252 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002253 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002254
John McCallc7e04da2010-05-28 18:45:08 +00002255 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2256 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002257
John McCallc7e04da2010-05-28 18:45:08 +00002258 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2259 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002260 // Look through any using declarations to find the underlying function.
2261 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002262
Chandler Carruthbd647292009-12-29 06:17:27 +00002263 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2264 if (!FDecl)
2265 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002266
2267 // Add the classes and namespaces associated with the parameter
2268 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002269 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002270 }
2271 }
2272}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002273
2274/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2275/// an acceptable non-member overloaded operator for a call whose
2276/// arguments have types T1 (and, if non-empty, T2). This routine
2277/// implements the check in C++ [over.match.oper]p3b2 concerning
2278/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002279static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002280IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2281 QualType T1, QualType T2,
2282 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002283 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2284 return true;
2285
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002286 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2287 return true;
2288
John McCall183700f2009-09-21 23:43:11 +00002289 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002290 if (Proto->getNumArgs() < 1)
2291 return false;
2292
2293 if (T1->isEnumeralType()) {
2294 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002295 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002296 return true;
2297 }
2298
2299 if (Proto->getNumArgs() < 2)
2300 return false;
2301
2302 if (!T2.isNull() && T2->isEnumeralType()) {
2303 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002304 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002305 return true;
2306 }
2307
2308 return false;
2309}
2310
John McCall7d384dd2009-11-18 07:57:50 +00002311NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002312 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002313 LookupNameKind NameKind,
2314 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002315 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002316 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002317 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002318}
2319
Douglas Gregor6e378de2009-04-23 23:18:26 +00002320/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002321ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002322 SourceLocation IdLoc,
2323 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002324 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002325 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002326 return cast_or_null<ObjCProtocolDecl>(D);
2327}
2328
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002329void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002330 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002331 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002332 // C++ [over.match.oper]p3:
2333 // -- The set of non-member candidates is the result of the
2334 // unqualified lookup of operator@ in the context of the
2335 // expression according to the usual rules for name lookup in
2336 // unqualified function calls (3.4.2) except that all member
2337 // functions are ignored. However, if no operand has a class
2338 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002339 // that have a first parameter of type T1 or "reference to
2340 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002341 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002342 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002343 // when T2 is an enumeration type, are candidate functions.
2344 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002345 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2346 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002348 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2349
John McCallf36e02d2009-10-09 21:13:30 +00002350 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002351 return;
2352
2353 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2354 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002355 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2356 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002357 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002358 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002359 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002360 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002361 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002362 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002363 // later?
2364 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002365 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002366 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002367 }
2368}
2369
Sean Huntc39b6bc2011-06-24 02:11:39 +00002370Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002371 CXXSpecialMember SM,
2372 bool ConstArg,
2373 bool VolatileArg,
2374 bool RValueThis,
2375 bool ConstThis,
2376 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002377 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002378 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002379 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002380 if (RValueThis || ConstThis || VolatileThis)
2381 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2382 "constructors and destructors always have unqualified lvalue this");
2383 if (ConstArg || VolatileArg)
2384 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2385 "parameter-less special members can't have qualified arguments");
2386
2387 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002388 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002389 ID.AddInteger(SM);
2390 ID.AddInteger(ConstArg);
2391 ID.AddInteger(VolatileArg);
2392 ID.AddInteger(RValueThis);
2393 ID.AddInteger(ConstThis);
2394 ID.AddInteger(VolatileThis);
2395
2396 void *InsertPoint;
2397 SpecialMemberOverloadResult *Result =
2398 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2399
2400 // This was already cached
2401 if (Result)
2402 return Result;
2403
Sean Hunt30543582011-06-07 00:11:58 +00002404 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2405 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002406 SpecialMemberCache.InsertNode(Result, InsertPoint);
2407
2408 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002409 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002410 DeclareImplicitDestructor(RD);
2411 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002412 assert(DD && "record without a destructor");
2413 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002414 Result->setKind(DD->isDeleted() ?
2415 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002416 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002417 return Result;
2418 }
2419
Sean Huntb320e0c2011-06-10 03:50:41 +00002420 // Prepare for overload resolution. Here we construct a synthetic argument
2421 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002422 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002423 DeclarationName Name;
2424 Expr *Arg = 0;
2425 unsigned NumArgs;
2426
Richard Smith704c8f72012-04-20 18:46:14 +00002427 QualType ArgType = CanTy;
2428 ExprValueKind VK = VK_LValue;
2429
Sean Huntb320e0c2011-06-10 03:50:41 +00002430 if (SM == CXXDefaultConstructor) {
2431 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2432 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002433 if (RD->needsImplicitDefaultConstructor())
2434 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002435 } else {
2436 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2437 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002438 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002439 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002440 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002441 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002442 } else {
2443 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002444 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002445 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002446 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002447 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002448 }
2449
Sean Huntb320e0c2011-06-10 03:50:41 +00002450 if (ConstArg)
2451 ArgType.addConst();
2452 if (VolatileArg)
2453 ArgType.addVolatile();
2454
2455 // This isn't /really/ specified by the standard, but it's implied
2456 // we should be working from an RValue in the case of move to ensure
2457 // that we prefer to bind to rvalue references, and an LValue in the
2458 // case of copy to ensure we don't bind to rvalue references.
2459 // Possibly an XValue is actually correct in the case of move, but
2460 // there is no semantic difference for class types in this restricted
2461 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002462 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002463 VK = VK_LValue;
2464 else
2465 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002466 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002467
Richard Smith704c8f72012-04-20 18:46:14 +00002468 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2469
2470 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002471 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002472 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002473 }
2474
2475 // Create the object argument
2476 QualType ThisTy = CanTy;
2477 if (ConstThis)
2478 ThisTy.addConst();
2479 if (VolatileThis)
2480 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002481 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002482 OpaqueValueExpr(SourceLocation(), ThisTy,
2483 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002484
2485 // Now we perform lookup on the name we computed earlier and do overload
2486 // resolution. Lookup is only performed directly into the class since there
2487 // will always be a (possibly implicit) declaration to shadow any others.
2488 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002489 DeclContext::lookup_result R = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002490
David Blaikie3bc93e32012-12-19 00:45:41 +00002491 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002492 "lookup for a constructor or assignment operator was empty");
David Blaikie3bc93e32012-12-19 00:45:41 +00002493 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002494 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002495
Sean Huntc39b6bc2011-06-24 02:11:39 +00002496 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002497 continue;
2498
Sean Huntc39b6bc2011-06-24 02:11:39 +00002499 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2500 // FIXME: [namespace.udecl]p15 says that we should only consider a
2501 // using declaration here if it does not match a declaration in the
2502 // derived class. We do not implement this correctly in other cases
2503 // either.
2504 Cand = U->getTargetDecl();
2505
2506 if (Cand->isInvalidDecl())
2507 continue;
2508 }
2509
2510 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002511 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002512 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002513 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2514 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002515 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002516 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2517 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002518 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002519 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002520 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2521 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002522 RD, 0, ThisTy, Classification,
2523 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002524 OCS, true);
2525 else
2526 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002527 0, llvm::makeArrayRef(&Arg, NumArgs),
2528 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002529 } else {
2530 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002531 }
2532 }
2533
2534 OverloadCandidateSet::iterator Best;
2535 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2536 case OR_Success:
2537 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002538 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002539 break;
2540
2541 case OR_Deleted:
2542 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002543 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002544 break;
2545
2546 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002547 Result->setMethod(0);
2548 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2549 break;
2550
Sean Huntb320e0c2011-06-10 03:50:41 +00002551 case OR_No_Viable_Function:
2552 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002553 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002554 break;
2555 }
2556
2557 return Result;
2558}
2559
2560/// \brief Look up the default constructor for the given class.
2561CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002562 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002563 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2564 false, false);
2565
2566 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002567}
2568
Sean Hunt661c67a2011-06-21 23:42:56 +00002569/// \brief Look up the copying constructor for the given class.
2570CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002571 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002572 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2573 "non-const, non-volatile qualifiers for copy ctor arg");
2574 SpecialMemberOverloadResult *Result =
2575 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2576 Quals & Qualifiers::Volatile, false, false, false);
2577
Sean Huntc530d172011-06-10 04:44:37 +00002578 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2579}
2580
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002581/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002582CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2583 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002584 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002585 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2586 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002587
2588 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2589}
2590
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002591/// \brief Look up the constructors for the given class.
2592DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002593 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002594 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002595 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002596 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002597 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002598 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002599 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002600 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002601 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002602
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002603 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2604 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2605 return Class->lookup(Name);
2606}
2607
Sean Hunt661c67a2011-06-21 23:42:56 +00002608/// \brief Look up the copying assignment operator for the given class.
2609CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2610 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002611 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002612 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2613 "non-const, non-volatile qualifiers for copy assignment arg");
2614 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2615 "non-const, non-volatile qualifiers for copy assignment this");
2616 SpecialMemberOverloadResult *Result =
2617 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2618 Quals & Qualifiers::Volatile, RValueThis,
2619 ThisQuals & Qualifiers::Const,
2620 ThisQuals & Qualifiers::Volatile);
2621
Sean Hunt661c67a2011-06-21 23:42:56 +00002622 return Result->getMethod();
2623}
2624
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002625/// \brief Look up the moving assignment operator for the given class.
2626CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002627 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002628 bool RValueThis,
2629 unsigned ThisQuals) {
2630 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2631 "non-const, non-volatile qualifiers for copy assignment this");
2632 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002633 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2634 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002635 ThisQuals & Qualifiers::Const,
2636 ThisQuals & Qualifiers::Volatile);
2637
2638 return Result->getMethod();
2639}
2640
Douglas Gregordb89f282010-07-01 22:47:18 +00002641/// \brief Look for the destructor of the given class.
2642///
Sean Huntc5c9b532011-06-03 21:10:40 +00002643/// During semantic analysis, this routine should be used in lieu of
2644/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002645///
2646/// \returns The destructor for this class.
2647CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002648 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2649 false, false, false,
2650 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002651}
2652
Richard Smith36f5cfe2012-03-09 08:00:36 +00002653/// LookupLiteralOperator - Determine which literal operator should be used for
2654/// a user-defined literal, per C++11 [lex.ext].
2655///
2656/// Normal overload resolution is not used to select which literal operator to
2657/// call for a user-defined literal. Look up the provided literal operator name,
2658/// and filter the results to the appropriate set for the given argument types.
2659Sema::LiteralOperatorLookupResult
2660Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2661 ArrayRef<QualType> ArgTys,
2662 bool AllowRawAndTemplate) {
2663 LookupName(R, S);
2664 assert(R.getResultKind() != LookupResult::Ambiguous &&
2665 "literal operator lookup can't be ambiguous");
2666
2667 // Filter the lookup results appropriately.
2668 LookupResult::Filter F = R.makeFilter();
2669
2670 bool FoundTemplate = false;
2671 bool FoundRaw = false;
2672 bool FoundExactMatch = false;
2673
2674 while (F.hasNext()) {
2675 Decl *D = F.next();
2676 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2677 D = USD->getTargetDecl();
2678
2679 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2680 bool IsRaw = false;
2681 bool IsExactMatch = false;
2682
Douglas Gregor7e0c2272013-04-10 05:18:00 +00002683 // If the declaration we found is invalid, skip it.
2684 if (D->isInvalidDecl()) {
2685 F.erase();
2686 continue;
2687 }
2688
Richard Smith36f5cfe2012-03-09 08:00:36 +00002689 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2690 if (FD->getNumParams() == 1 &&
2691 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2692 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002693 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002694 IsExactMatch = true;
2695 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2696 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2697 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2698 IsExactMatch = false;
2699 break;
2700 }
2701 }
2702 }
2703 }
2704
2705 if (IsExactMatch) {
2706 FoundExactMatch = true;
2707 AllowRawAndTemplate = false;
2708 if (FoundRaw || FoundTemplate) {
2709 // Go through again and remove the raw and template decls we've
2710 // already found.
2711 F.restart();
2712 FoundRaw = FoundTemplate = false;
2713 }
2714 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2715 FoundTemplate |= IsTemplate;
2716 FoundRaw |= IsRaw;
2717 } else {
2718 F.erase();
2719 }
2720 }
2721
2722 F.done();
2723
2724 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2725 // parameter type, that is used in preference to a raw literal operator
2726 // or literal operator template.
2727 if (FoundExactMatch)
2728 return LOLR_Cooked;
2729
2730 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2731 // operator template, but not both.
2732 if (FoundRaw && FoundTemplate) {
2733 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2734 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2735 Decl *D = *I;
2736 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2737 D = USD->getTargetDecl();
2738 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2739 D = FunTmpl->getTemplatedDecl();
2740 NoteOverloadCandidate(cast<FunctionDecl>(D));
2741 }
2742 return LOLR_Error;
2743 }
2744
2745 if (FoundRaw)
2746 return LOLR_Raw;
2747
2748 if (FoundTemplate)
2749 return LOLR_Template;
2750
2751 // Didn't find anything we could use.
2752 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2753 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2754 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2755 return LOLR_Error;
2756}
2757
John McCall7edb5fd2010-01-26 07:16:45 +00002758void ADLResult::insert(NamedDecl *New) {
2759 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2760
2761 // If we haven't yet seen a decl for this key, or the last decl
2762 // was exactly this one, we're done.
2763 if (Old == 0 || Old == New) {
2764 Old = New;
2765 return;
2766 }
2767
2768 // Otherwise, decide which is a more recent redeclaration.
2769 FunctionDecl *OldFD, *NewFD;
2770 if (isa<FunctionTemplateDecl>(New)) {
2771 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2772 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2773 } else {
2774 OldFD = cast<FunctionDecl>(Old);
2775 NewFD = cast<FunctionDecl>(New);
2776 }
2777
2778 FunctionDecl *Cursor = NewFD;
2779 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002780 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002781
2782 // If we got to the end without finding OldFD, OldFD is the newer
2783 // declaration; leave things as they are.
2784 if (!Cursor) return;
2785
2786 // If we do find OldFD, then NewFD is newer.
2787 if (Cursor == OldFD) break;
2788
2789 // Otherwise, keep looking.
2790 }
2791
2792 Old = New;
2793}
2794
Sebastian Redl644be852009-10-23 19:23:15 +00002795void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm834c0582013-08-09 18:02:13 +00002796 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002797 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002798 // Find all of the associated namespaces and classes based on the
2799 // arguments we have.
2800 AssociatedNamespaceSet AssociatedNamespaces;
2801 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002802 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002803 AssociatedNamespaces,
2804 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002805
Sebastian Redl644be852009-10-23 19:23:15 +00002806 QualType T1, T2;
2807 if (Operator) {
2808 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002809 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002810 T2 = Args[1]->getType();
2811 }
2812
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002813 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002814 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2815 // and let Y be the lookup set produced by argument dependent
2816 // lookup (defined as follows). If X contains [...] then Y is
2817 // empty. Otherwise Y is the set of declarations found in the
2818 // namespaces associated with the argument types as described
2819 // below. The set of declarations found by the lookup of the name
2820 // is the union of X and Y.
2821 //
2822 // Here, we compute Y and add its members to the overloaded
2823 // candidate set.
2824 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002825 NSEnd = AssociatedNamespaces.end();
2826 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002827 // When considering an associated namespace, the lookup is the
2828 // same as the lookup performed when the associated namespace is
2829 // used as a qualifier (3.4.3.2) except that:
2830 //
2831 // -- Any using-directives in the associated namespace are
2832 // ignored.
2833 //
John McCall6ff07852009-08-07 22:18:02 +00002834 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002835 // associated classes are visible within their respective
2836 // namespaces even if they are not visible during an ordinary
2837 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002838 DeclContext::lookup_result R = (*NS)->lookup(Name);
2839 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2840 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002841 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002842 // If the only declaration here is an ordinary friend, consider
2843 // it only if it was declared in an associated classes.
2844 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
Richard Smith22050f22013-07-17 23:53:16 +00002845 bool DeclaredInAssociatedClass = false;
2846 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2847 DeclContext *LexDC = DI->getLexicalDeclContext();
2848 if (isa<CXXRecordDecl>(LexDC) &&
2849 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2850 DeclaredInAssociatedClass = true;
2851 break;
2852 }
2853 }
2854 if (!DeclaredInAssociatedClass)
John McCall3f9a8a62009-08-11 06:59:38 +00002855 continue;
2856 }
Mike Stump1eb44332009-09-09 15:08:12 +00002857
John McCalla113e722010-01-26 06:04:06 +00002858 if (isa<UsingShadowDecl>(D))
2859 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002860
John McCalla113e722010-01-26 06:04:06 +00002861 if (isa<FunctionDecl>(D)) {
2862 if (Operator &&
2863 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2864 T1, T2, Context))
2865 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002866 } else if (!isa<FunctionTemplateDecl>(D))
2867 continue;
2868
2869 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002870 }
2871 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002872}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002873
2874//----------------------------------------------------------------------------
2875// Search for all visible declarations.
2876//----------------------------------------------------------------------------
2877VisibleDeclConsumer::~VisibleDeclConsumer() { }
2878
2879namespace {
2880
2881class ShadowContextRAII;
2882
2883class VisibleDeclsRecord {
2884public:
2885 /// \brief An entry in the shadow map, which is optimized to store a
2886 /// single declaration (the common case) but can also store a list
2887 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002888 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002889
2890private:
2891 /// \brief A mapping from declaration names to the declarations that have
2892 /// this name within a particular scope.
2893 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2894
2895 /// \brief A list of shadow maps, which is used to model name hiding.
2896 std::list<ShadowMap> ShadowMaps;
2897
2898 /// \brief The declaration contexts we have already visited.
2899 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2900
2901 friend class ShadowContextRAII;
2902
2903public:
2904 /// \brief Determine whether we have already visited this context
2905 /// (and, if not, note that we are going to visit that context now).
2906 bool visitedContext(DeclContext *Ctx) {
2907 return !VisitedContexts.insert(Ctx);
2908 }
2909
Douglas Gregor8071e422010-08-15 06:18:01 +00002910 bool alreadyVisitedContext(DeclContext *Ctx) {
2911 return VisitedContexts.count(Ctx);
2912 }
2913
Douglas Gregor546be3c2009-12-30 17:04:44 +00002914 /// \brief Determine whether the given declaration is hidden in the
2915 /// current scope.
2916 ///
2917 /// \returns the declaration that hides the given declaration, or
2918 /// NULL if no such declaration exists.
2919 NamedDecl *checkHidden(NamedDecl *ND);
2920
2921 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002922 void add(NamedDecl *ND) {
2923 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2924 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002925};
2926
2927/// \brief RAII object that records when we've entered a shadow context.
2928class ShadowContextRAII {
2929 VisibleDeclsRecord &Visible;
2930
2931 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2932
2933public:
2934 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2935 Visible.ShadowMaps.push_back(ShadowMap());
2936 }
2937
2938 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002939 Visible.ShadowMaps.pop_back();
2940 }
2941};
2942
2943} // end anonymous namespace
2944
Douglas Gregor546be3c2009-12-30 17:04:44 +00002945NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002946 // Look through using declarations.
2947 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002948
Douglas Gregor546be3c2009-12-30 17:04:44 +00002949 unsigned IDNS = ND->getIdentifierNamespace();
2950 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2951 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2952 SM != SMEnd; ++SM) {
2953 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2954 if (Pos == SM->end())
2955 continue;
2956
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002957 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002958 IEnd = Pos->second.end();
2959 I != IEnd; ++I) {
2960 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002961 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002962 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002963 Decl::IDNS_ObjCProtocol)))
2964 continue;
2965
2966 // Protocols are in distinct namespaces from everything else.
2967 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2968 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2969 (*I)->getIdentifierNamespace() != IDNS)
2970 continue;
2971
Douglas Gregor0cc84042010-01-14 15:47:35 +00002972 // Functions and function templates in the same scope overload
2973 // rather than hide. FIXME: Look for hiding based on function
2974 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002975 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002976 ND->isFunctionOrFunctionTemplate() &&
2977 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002978 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002979
Douglas Gregor546be3c2009-12-30 17:04:44 +00002980 // We've found a declaration that hides this one.
2981 return *I;
2982 }
2983 }
2984
2985 return 0;
2986}
2987
2988static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2989 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002990 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002991 VisibleDeclConsumer &Consumer,
2992 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002993 if (!Ctx)
2994 return;
2995
Douglas Gregor546be3c2009-12-30 17:04:44 +00002996 // Make sure we don't visit the same context twice.
2997 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2998 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002999
Douglas Gregor4923aa22010-07-02 20:37:36 +00003000 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3001 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3002
Douglas Gregor546be3c2009-12-30 17:04:44 +00003003 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00003004 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
3005 LEnd = Ctx->lookups_end();
3006 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003007 DeclContext::lookup_result R = *L;
3008 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3009 ++I) {
3010 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00003011 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003012 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003013 Visited.add(ND);
3014 }
Douglas Gregor70c23352010-12-09 21:44:02 +00003015 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003016 }
3017 }
3018
3019 // Traverse using directives for qualified name lookup.
3020 if (QualifiedNameLookup) {
3021 ShadowContextRAII Shadow(Visited);
3022 DeclContext::udir_iterator I, E;
3023 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003024 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003025 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003026 }
3027 }
3028
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003029 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003030 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00003031 if (!Record->hasDefinition())
3032 return;
3033
Douglas Gregor546be3c2009-12-30 17:04:44 +00003034 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
3035 BEnd = Record->bases_end();
3036 B != BEnd; ++B) {
3037 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003038
Douglas Gregor546be3c2009-12-30 17:04:44 +00003039 // Don't look into dependent bases, because name lookup can't look
3040 // there anyway.
3041 if (BaseType->isDependentType())
3042 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003043
Douglas Gregor546be3c2009-12-30 17:04:44 +00003044 const RecordType *Record = BaseType->getAs<RecordType>();
3045 if (!Record)
3046 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003047
Douglas Gregor546be3c2009-12-30 17:04:44 +00003048 // FIXME: It would be nice to be able to determine whether referencing
3049 // a particular member would be ambiguous. For example, given
3050 //
3051 // struct A { int member; };
3052 // struct B { int member; };
3053 // struct C : A, B { };
3054 //
3055 // void f(C *c) { c->### }
3056 //
3057 // accessing 'member' would result in an ambiguity. However, we
3058 // could be smart enough to qualify the member with the base
3059 // class, e.g.,
3060 //
3061 // c->B::member
3062 //
3063 // or
3064 //
3065 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003066
Douglas Gregor546be3c2009-12-30 17:04:44 +00003067 // Find results in this base class (and its bases).
3068 ShadowContextRAII Shadow(Visited);
3069 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003070 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003071 }
3072 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003073
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003074 // Traverse the contexts of Objective-C classes.
3075 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3076 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00003077 for (ObjCInterfaceDecl::visible_categories_iterator
3078 Cat = IFace->visible_categories_begin(),
3079 CatEnd = IFace->visible_categories_end();
3080 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003081 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00003082 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003083 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003084 }
3085
3086 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003087 for (ObjCInterfaceDecl::all_protocol_iterator
3088 I = IFace->all_referenced_protocol_begin(),
3089 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003090 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003091 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003092 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003093 }
3094
3095 // Traverse the superclass.
3096 if (IFace->getSuperClass()) {
3097 ShadowContextRAII Shadow(Visited);
3098 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003099 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003100 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003101
Douglas Gregorc220a182010-04-19 18:02:19 +00003102 // If there is an implementation, traverse it. We do this to find
3103 // synthesized ivars.
3104 if (IFace->getImplementation()) {
3105 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003106 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00003107 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00003108 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003109 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3110 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3111 E = Protocol->protocol_end(); I != E; ++I) {
3112 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003113 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003114 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003115 }
3116 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3117 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3118 E = Category->protocol_end(); I != E; ++I) {
3119 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003120 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003121 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003122 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003123
Douglas Gregorc220a182010-04-19 18:02:19 +00003124 // If there is an implementation, traverse it.
3125 if (Category->getImplementation()) {
3126 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003127 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00003128 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003129 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003130 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003131}
3132
3133static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3134 UnqualUsingDirectiveSet &UDirs,
3135 VisibleDeclConsumer &Consumer,
3136 VisibleDeclsRecord &Visited) {
3137 if (!S)
3138 return;
3139
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003140 if (!S->getEntity() ||
3141 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00003142 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00003143 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3144 // Walk through the declarations in this Scope.
3145 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3146 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003147 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003148 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003149 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003150 Visited.add(ND);
3151 }
3152 }
3153 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003154
Douglas Gregor711be1e2010-03-15 14:33:29 +00003155 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003156 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003157 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003158 // Look into this scope's declaration context, along with any of its
3159 // parent lookup contexts (e.g., enclosing classes), up to the point
3160 // where we hit the context stored in the next outer scope.
3161 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003162 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003163
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003164 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003165 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003166 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3167 if (Method->isInstanceMethod()) {
3168 // For instance methods, look for ivars in the method's interface.
3169 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3170 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003171 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003172 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00003173 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003174 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003175 }
3176
3177 // We've already performed all of the name lookup that we need
3178 // to for Objective-C methods; the next context will be the
3179 // outer scope.
3180 break;
3181 }
3182
Douglas Gregor546be3c2009-12-30 17:04:44 +00003183 if (Ctx->isFunctionOrMethod())
3184 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003185
3186 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003187 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003188 }
3189 } else if (!S->getParent()) {
3190 // Look into the translation unit scope. We walk through the translation
3191 // unit's declaration context, because the Scope itself won't have all of
3192 // the declarations if we loaded a precompiled header.
3193 // FIXME: We would like the translation unit's Scope object to point to the
3194 // translation unit, so we don't need this special "if" branch. However,
3195 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003196 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003197 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003198 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003199 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003200 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003201 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202 }
3203
Douglas Gregor546be3c2009-12-30 17:04:44 +00003204 if (Entity) {
3205 // Lookup visible declarations in any namespaces found by using
3206 // directives.
3207 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3208 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3209 for (; UI != UEnd; ++UI)
3210 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003212 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003213 }
3214
3215 // Lookup names in the parent scope.
3216 ShadowContextRAII Shadow(Visited);
3217 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3218}
3219
3220void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003221 VisibleDeclConsumer &Consumer,
3222 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003223 // Determine the set of using directives available during
3224 // unqualified name lookup.
3225 Scope *Initial = S;
3226 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003227 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003228 // Find the first namespace or translation-unit scope.
3229 while (S && !isNamespaceOrTranslationUnitScope(S))
3230 S = S->getParent();
3231
3232 UDirs.visitScopeChain(Initial, S);
3233 }
3234 UDirs.done();
3235
3236 // Look for visible declarations.
3237 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3238 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003239 if (!IncludeGlobalScope)
3240 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003241 ShadowContextRAII Shadow(Visited);
3242 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3243}
3244
3245void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003246 VisibleDeclConsumer &Consumer,
3247 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003248 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3249 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003250 if (!IncludeGlobalScope)
3251 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003252 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003253 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003254 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003255}
3256
Chris Lattner4ae493c2011-02-18 02:08:43 +00003257/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003258/// If GnuLabelLoc is a valid source location, then this is a definition
3259/// of an __label__ label name, otherwise it is a normal label definition
3260/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003261LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003262 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003263 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003264 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003265
3266 if (GnuLabelLoc.isValid()) {
3267 // Local label definitions always shadow existing labels.
3268 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3269 Scope *S = CurScope;
3270 PushOnScopeChains(Res, S, true);
3271 return cast<LabelDecl>(Res);
3272 }
3273
3274 // Not a GNU local label.
3275 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3276 // If we found a label, check to see if it is in the same context as us.
3277 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003278 if (Res && Res->getDeclContext() != CurContext)
3279 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003280 if (Res == 0) {
3281 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003282 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3283 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003284 assert(S && "Not in a function?");
3285 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003286 }
Chris Lattner337e5502011-02-18 01:27:55 +00003287 return cast<LabelDecl>(Res);
3288}
3289
3290//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003291// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003292//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003293
3294namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003295
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003296typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003297typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003298typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003299
3300static const unsigned MaxTypoDistanceResultSets = 5;
3301
Douglas Gregor546be3c2009-12-30 17:04:44 +00003302class TypoCorrectionConsumer : public VisibleDeclConsumer {
3303 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003304 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003305
3306 /// \brief The results found that have the smallest edit distance
3307 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003308 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003309 /// The pointer value being set to the current DeclContext indicates
3310 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003311 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003312
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003313 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003314
Douglas Gregor546be3c2009-12-30 17:04:44 +00003315public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003316 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003317 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003318 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003319
Erik Verbruggend1205962011-10-06 07:27:49 +00003320 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3321 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003322 void FoundName(StringRef Name);
3323 void addKeywordResult(StringRef Keyword);
3324 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003325 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003326 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003327
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003328 typedef TypoResultsMap::iterator result_iterator;
3329 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003330 distance_iterator begin() { return CorrectionResults.begin(); }
3331 distance_iterator end() { return CorrectionResults.end(); }
3332 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3333 unsigned size() const { return CorrectionResults.size(); }
3334 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003335
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003336 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003337 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003338 }
3339
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003340 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003341 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003342 return (std::numeric_limits<unsigned>::max)();
3343
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003344 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003345 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003346 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003347
3348 TypoResultsMap &getBestResults() {
3349 return CorrectionResults.begin()->second;
3350 }
3351
Douglas Gregor546be3c2009-12-30 17:04:44 +00003352};
3353
3354}
3355
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003356void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003357 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003358 // Don't consider hidden names for typo correction.
3359 if (Hiding)
3360 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003361
Douglas Gregor546be3c2009-12-30 17:04:44 +00003362 // Only consider entities with identifiers for names, ignoring
3363 // special names (constructors, overloaded operators, selectors,
3364 // etc.).
3365 IdentifierInfo *Name = ND->getIdentifier();
3366 if (!Name)
3367 return;
3368
Douglas Gregor95f42922010-10-14 22:11:03 +00003369 FoundName(Name->getName());
3370}
3371
Chris Lattner5f9e2722011-07-23 10:55:15 +00003372void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003373 // Use a simple length-based heuristic to determine the minimum possible
3374 // edit distance. If the minimum isn't good enough, bail out early.
3375 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003376 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003377 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003378
Douglas Gregora1194772010-10-19 22:14:33 +00003379 // Compute an upper bound on the allowable edit distance, so that the
3380 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003381 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003382
Douglas Gregor546be3c2009-12-30 17:04:44 +00003383 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003384 // entity, and add the identifier to the list of results.
3385 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003386}
3387
Chris Lattner5f9e2722011-07-23 10:55:15 +00003388void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003389 // Compute the edit distance between the typo and this keyword,
3390 // and add the keyword to the list of results.
3391 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003392}
3393
Chris Lattner5f9e2722011-07-23 10:55:15 +00003394void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003395 NamedDecl *ND,
3396 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003397 NestedNameSpecifier *NNS,
3398 bool isKeyword) {
3399 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3400 if (isKeyword) TC.makeKeyword();
3401 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003402}
3403
3404void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003405 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003406 TypoResultList &CList =
3407 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003408
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003409 if (!CList.empty() && !CList.back().isResolved())
3410 CList.pop_back();
3411 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3412 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3413 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3414 RI != RIEnd; ++RI) {
3415 // If the Correction refers to a decl already in the result list,
3416 // replace the existing result if the string representation of Correction
3417 // comes before the current result alphabetically, then stop as there is
3418 // nothing more to be done to add Correction to the candidate set.
3419 if (RI->getCorrectionDecl() == NewND) {
3420 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3421 *RI = Correction;
3422 return;
3423 }
3424 }
3425 }
3426 if (CList.empty() || Correction.isResolved())
3427 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003428
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003429 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3430 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003431}
3432
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003433// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3434// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3435// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3436static void getNestedNameSpecifierIdentifiers(
3437 NestedNameSpecifier *NNS,
3438 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3439 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3440 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3441 else
3442 Identifiers.clear();
3443
3444 const IdentifierInfo *II = NULL;
3445
3446 switch (NNS->getKind()) {
3447 case NestedNameSpecifier::Identifier:
3448 II = NNS->getAsIdentifier();
3449 break;
3450
3451 case NestedNameSpecifier::Namespace:
3452 if (NNS->getAsNamespace()->isAnonymousNamespace())
3453 return;
3454 II = NNS->getAsNamespace()->getIdentifier();
3455 break;
3456
3457 case NestedNameSpecifier::NamespaceAlias:
3458 II = NNS->getAsNamespaceAlias()->getIdentifier();
3459 break;
3460
3461 case NestedNameSpecifier::TypeSpecWithTemplate:
3462 case NestedNameSpecifier::TypeSpec:
3463 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3464 break;
3465
3466 case NestedNameSpecifier::Global:
3467 return;
3468 }
3469
3470 if (II)
3471 Identifiers.push_back(II);
3472}
3473
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003474namespace {
3475
3476class SpecifierInfo {
3477 public:
3478 DeclContext* DeclCtx;
3479 NestedNameSpecifier* NameSpecifier;
3480 unsigned EditDistance;
3481
3482 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3483 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3484};
3485
Chris Lattner5f9e2722011-07-23 10:55:15 +00003486typedef SmallVector<DeclContext*, 4> DeclContextList;
3487typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003488
3489class NamespaceSpecifierSet {
3490 ASTContext &Context;
3491 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003492 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3493 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003494 bool isSorted;
3495
3496 SpecifierInfoList Specifiers;
3497 llvm::SmallSetVector<unsigned, 4> Distances;
3498 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3499
3500 /// \brief Helper for building the list of DeclContexts between the current
3501 /// context and the top of the translation unit
3502 static DeclContextList BuildContextChain(DeclContext *Start);
3503
3504 void SortNamespaces();
3505
3506 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003507 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3508 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003509 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003510 isSorted(false) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003511 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3512 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3513 CurNameSpecifierIdentifiers);
3514 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003515 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003516 // context.
3517 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3518 CEnd = CurContextChain.rend();
3519 C != CEnd; ++C) {
3520 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3521 CurContextIdentifiers.push_back(ND->getIdentifier());
3522 }
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003523
3524 // Add the global context as a NestedNameSpecifier
3525 Distances.insert(1);
3526 DistanceMap[1].push_back(
3527 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3528 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003529 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003530
3531 /// \brief Add the namespace to the set, computing the corresponding
3532 /// NestedNameSpecifier and its distance in the process.
3533 void AddNamespace(NamespaceDecl *ND);
3534
3535 typedef SpecifierInfoList::iterator iterator;
3536 iterator begin() {
3537 if (!isSorted) SortNamespaces();
3538 return Specifiers.begin();
3539 }
3540 iterator end() { return Specifiers.end(); }
3541};
3542
3543}
3544
3545DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0db9d202013-04-08 21:55:21 +00003546 assert(Start && "Building a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003547 DeclContextList Chain;
3548 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3549 DC = DC->getLookupParent()) {
3550 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3551 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3552 !(ND && ND->isAnonymousNamespace()))
3553 Chain.push_back(DC->getPrimaryContext());
3554 }
3555 return Chain;
3556}
3557
3558void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003559 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003560 sortedDistances.append(Distances.begin(), Distances.end());
3561
3562 if (sortedDistances.size() > 1)
3563 std::sort(sortedDistances.begin(), sortedDistances.end());
3564
3565 Specifiers.clear();
Craig Topper09d19ef2013-07-04 03:08:24 +00003566 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3567 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003568 DI != DIEnd; ++DI) {
3569 SpecifierInfoList &SpecList = DistanceMap[*DI];
3570 Specifiers.append(SpecList.begin(), SpecList.end());
3571 }
3572
3573 isSorted = true;
3574}
3575
3576void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003577 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003578 NestedNameSpecifier *NNS = NULL;
3579 unsigned NumSpecifiers = 0;
3580 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003581 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003582
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003583 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003584 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3585 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003586 C != CEnd && !NamespaceDeclChain.empty() &&
3587 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003588 NamespaceDeclChain.pop_back();
3589 }
3590
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003591 // Add an explicit leading '::' specifier if needed.
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00003592 if (NamespaceDeclChain.empty()) {
3593 NamespaceDeclChain = FullNamespaceDeclChain;
3594 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3595 } else if (NamespaceDecl *ND =
3596 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003597 IdentifierInfo *Name = ND->getIdentifier();
3598 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3599 Name) != CurContextIdentifiers.end() ||
3600 std::find(CurNameSpecifierIdentifiers.begin(),
3601 CurNameSpecifierIdentifiers.end(),
3602 Name) != CurNameSpecifierIdentifiers.end()) {
3603 NamespaceDeclChain = FullNamespaceDeclChain;
3604 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3605 }
3606 }
3607
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003608 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3609 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3610 CEnd = NamespaceDeclChain.rend();
3611 C != CEnd; ++C) {
3612 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3613 if (ND) {
3614 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3615 ++NumSpecifiers;
3616 }
3617 }
3618
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003619 // If the built NestedNameSpecifier would be replacing an existing
3620 // NestedNameSpecifier, use the number of component identifiers that
3621 // would need to be changed as the edit distance instead of the number
3622 // of components in the built NestedNameSpecifier.
3623 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3624 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3625 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3626 NumSpecifiers = llvm::ComputeEditDistance(
Robert Wilhelm834c0582013-08-09 18:02:13 +00003627 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3628 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003629 }
3630
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003631 isSorted = false;
3632 Distances.insert(NumSpecifiers);
3633 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003634}
3635
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003636/// \brief Perform name lookup for a possible result for typo correction.
3637static void LookupPotentialTypoResult(Sema &SemaRef,
3638 LookupResult &Res,
3639 IdentifierInfo *Name,
3640 Scope *S, CXXScopeSpec *SS,
3641 DeclContext *MemberContext,
3642 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003643 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003644 Res.suppressDiagnostics();
3645 Res.clear();
3646 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003647 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003648 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003649 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003650 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3651 Res.addDecl(Ivar);
3652 Res.resolveKind();
3653 return;
3654 }
3655 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003656
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003657 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3658 Res.addDecl(Prop);
3659 Res.resolveKind();
3660 return;
3661 }
3662 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003663
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003664 SemaRef.LookupQualifiedName(Res, MemberContext);
3665 return;
3666 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003667
3668 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003669 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003670
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003671 // Fake ivar lookup; this should really be part of
3672 // LookupParsedName.
3673 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3674 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003675 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003676 (Res.isSingleResult() &&
3677 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003678 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003679 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3680 Res.addDecl(IV);
3681 Res.resolveKind();
3682 }
3683 }
3684 }
3685}
3686
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003687/// \brief Add keywords to the consumer as possible typo corrections.
3688static void AddKeywordsToConsumer(Sema &SemaRef,
3689 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003690 Scope *S, CorrectionCandidateCallback &CCC,
3691 bool AfterNestedNameSpecifier) {
3692 if (AfterNestedNameSpecifier) {
3693 // For 'X::', we know exactly which keywords can appear next.
3694 Consumer.addKeywordResult("template");
3695 if (CCC.WantExpressionKeywords)
3696 Consumer.addKeywordResult("operator");
3697 return;
3698 }
3699
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003700 if (CCC.WantObjCSuper)
3701 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003702
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003703 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003704 // Add type-specifier keywords to the set of results.
Craig Topper3aa29df2013-07-15 08:24:27 +00003705 static const char *const CTypeSpecs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003706 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003707 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003708 "_Complex", "_Imaginary",
3709 // storage-specifiers as well
3710 "extern", "inline", "static", "typedef"
3711 };
3712
Craig Topperb9602322013-07-15 03:38:40 +00003713 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003714 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3715 Consumer.addKeywordResult(CTypeSpecs[I]);
3716
David Blaikie4e4d0842012-03-11 07:00:24 +00003717 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003718 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003719 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003720 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003721 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003722 Consumer.addKeywordResult("_Bool");
3723
David Blaikie4e4d0842012-03-11 07:00:24 +00003724 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003725 Consumer.addKeywordResult("class");
3726 Consumer.addKeywordResult("typename");
3727 Consumer.addKeywordResult("wchar_t");
3728
Richard Smith80ad52f2013-01-02 11:42:31 +00003729 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003730 Consumer.addKeywordResult("char16_t");
3731 Consumer.addKeywordResult("char32_t");
3732 Consumer.addKeywordResult("constexpr");
3733 Consumer.addKeywordResult("decltype");
3734 Consumer.addKeywordResult("thread_local");
3735 }
3736 }
3737
David Blaikie4e4d0842012-03-11 07:00:24 +00003738 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003739 Consumer.addKeywordResult("typeof");
3740 }
3741
David Blaikie4e4d0842012-03-11 07:00:24 +00003742 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003743 Consumer.addKeywordResult("const_cast");
3744 Consumer.addKeywordResult("dynamic_cast");
3745 Consumer.addKeywordResult("reinterpret_cast");
3746 Consumer.addKeywordResult("static_cast");
3747 }
3748
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003749 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003750 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003751 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003752 Consumer.addKeywordResult("false");
3753 Consumer.addKeywordResult("true");
3754 }
3755
David Blaikie4e4d0842012-03-11 07:00:24 +00003756 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topper3aa29df2013-07-15 08:24:27 +00003757 static const char *const CXXExprs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003758 "delete", "new", "operator", "throw", "typeid"
3759 };
Craig Topperb9602322013-07-15 03:38:40 +00003760 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003761 for (unsigned I = 0; I != NumCXXExprs; ++I)
3762 Consumer.addKeywordResult(CXXExprs[I]);
3763
3764 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3765 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3766 Consumer.addKeywordResult("this");
3767
Richard Smith80ad52f2013-01-02 11:42:31 +00003768 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003769 Consumer.addKeywordResult("alignof");
3770 Consumer.addKeywordResult("nullptr");
3771 }
3772 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003773
3774 if (SemaRef.getLangOpts().C11) {
3775 // FIXME: We should not suggest _Alignof if the alignof macro
3776 // is present.
3777 Consumer.addKeywordResult("_Alignof");
3778 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003779 }
3780
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003781 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003782 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3783 // Statements.
Craig Topper3aa29df2013-07-15 08:24:27 +00003784 static const char *const CStmts[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003785 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Topperb9602322013-07-15 03:38:40 +00003786 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003787 for (unsigned I = 0; I != NumCStmts; ++I)
3788 Consumer.addKeywordResult(CStmts[I]);
3789
David Blaikie4e4d0842012-03-11 07:00:24 +00003790 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003791 Consumer.addKeywordResult("catch");
3792 Consumer.addKeywordResult("try");
3793 }
3794
3795 if (S && S->getBreakParent())
3796 Consumer.addKeywordResult("break");
3797
3798 if (S && S->getContinueParent())
3799 Consumer.addKeywordResult("continue");
3800
3801 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3802 Consumer.addKeywordResult("case");
3803 Consumer.addKeywordResult("default");
3804 }
3805 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003806 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003807 Consumer.addKeywordResult("namespace");
3808 Consumer.addKeywordResult("template");
3809 }
3810
3811 if (S && S->isClassScope()) {
3812 Consumer.addKeywordResult("explicit");
3813 Consumer.addKeywordResult("friend");
3814 Consumer.addKeywordResult("mutable");
3815 Consumer.addKeywordResult("private");
3816 Consumer.addKeywordResult("protected");
3817 Consumer.addKeywordResult("public");
3818 Consumer.addKeywordResult("virtual");
3819 }
3820 }
3821
David Blaikie4e4d0842012-03-11 07:00:24 +00003822 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003823 Consumer.addKeywordResult("using");
3824
Richard Smith80ad52f2013-01-02 11:42:31 +00003825 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003826 Consumer.addKeywordResult("static_assert");
3827 }
3828 }
3829}
3830
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003831static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3832 TypoCorrection &Candidate) {
3833 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3834 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3835}
3836
Douglas Gregor546be3c2009-12-30 17:04:44 +00003837/// \brief Try to "correct" a typo in the source code by finding
3838/// visible declarations whose names are similar to the name that was
3839/// present in the source code.
3840///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003841/// \param TypoName the \c DeclarationNameInfo structure that contains
3842/// the name that was present in the source code along with its location.
3843///
3844/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003845///
3846/// \param S the scope in which name lookup occurs.
3847///
3848/// \param SS the nested-name-specifier that precedes the name we're
3849/// looking for, if present.
3850///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003851/// \param CCC A CorrectionCandidateCallback object that provides further
3852/// validation of typo correction candidates. It also provides flags for
3853/// determining the set of keywords permitted.
3854///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003855/// \param MemberContext if non-NULL, the context in which to look for
3856/// a member access expression.
3857///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003858/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003859/// the nested-name-specifier SS.
3860///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003861/// \param OPT when non-NULL, the search for visible declarations will
3862/// also walk the protocols in the qualified interfaces of \p OPT.
3863///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003864/// \returns a \c TypoCorrection containing the corrected name if the typo
3865/// along with information such as the \c NamedDecl where the corrected name
3866/// was declared, and any additional \c NestedNameSpecifier needed to access
3867/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3868TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3869 Sema::LookupNameKind LookupKind,
3870 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003871 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003872 DeclContext *MemberContext,
3873 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003874 const ObjCObjectPointerType *OPT) {
Kaelyn Uhrain70571f42013-08-12 19:54:38 +00003875 // Always let the ExternalSource have the first chance at correction, even
3876 // if we would otherwise have given up.
3877 if (ExternalSource) {
3878 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
3879 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
3880 return Correction;
3881 }
3882
David Blaikie4e4d0842012-03-11 07:00:24 +00003883 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003884 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885
Francois Pichet4d604d62011-12-03 15:55:29 +00003886 // In Microsoft mode, don't perform typo correction in a template member
3887 // function dependent context because it interferes with the "lookup into
3888 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003889 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003890 isa<CXXMethodDecl>(CurContext))
3891 return TypoCorrection();
3892
Douglas Gregor546be3c2009-12-30 17:04:44 +00003893 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003894 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003895 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003896 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003897
3898 // If the scope specifier itself was invalid, don't try to correct
3899 // typos.
3900 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003901 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003902
3903 // Never try to correct typos during template deduction or
3904 // instantiation.
3905 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003906 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003907
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003908 // Don't try to correct 'super'.
3909 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3910 return TypoCorrection();
3911
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003912 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003913
3914 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003915
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003916 // If a callback object considers an empty typo correction candidate to be
3917 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003918 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003919 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003920
Douglas Gregoraaf87162010-04-14 20:04:41 +00003921 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003922 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003923 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003924 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003925 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003926
3927 // Look in qualified interfaces.
3928 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003929 for (ObjCObjectPointerType::qual_iterator
3930 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003931 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003932 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003933 }
3934 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003935 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3936 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003937 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003939 // Provide a stop gap for files that are just seriously broken. Trying
3940 // to correct all typos can turn into a HUGE performance penalty, causing
3941 // some files to take minutes to get rejected by the parser.
3942 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003943 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003944 ++TyposCorrected;
3945
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003946 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003947 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003948 IsUnqualifiedLookup = true;
3949 UnqualifiedTyposCorrectedMap::iterator Cached
3950 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003951 if (Cached != UnqualifiedTyposCorrected.end()) {
3952 // Add the cached value, unless it's a keyword or fails validation. In the
3953 // keyword case, we'll end up adding the keyword below.
3954 if (Cached->second) {
3955 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003956 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003957 Consumer.addCorrection(Cached->second);
3958 } else {
3959 // Only honor no-correction cache hits when a callback that will validate
3960 // correction candidates is not being used.
3961 if (!ValidatingCallback)
3962 return TypoCorrection();
3963 }
3964 }
3965 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003966 // Provide a stop gap for files that are just seriously broken. Trying
3967 // to correct all typos can turn into a HUGE performance penalty, causing
3968 // some files to take minutes to get rejected by the parser.
3969 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003970 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003971 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003972 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003973
Douglas Gregor01798682012-03-26 16:54:18 +00003974 // Determine whether we are going to search in the various namespaces for
3975 // corrections.
3976 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00003977 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00003978 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003979 // In a few cases we *only* want to search for corrections bases on just
3980 // adding or changing the nested name specifier.
3981 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00003982
3983 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003984 // For unqualified lookup, look through all of the names that we have
3985 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003986 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003987 for (IdentifierTable::iterator I = Context.Idents.begin(),
3988 IEnd = Context.Idents.end();
3989 I != IEnd; ++I)
3990 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003991
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003992 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003993 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003994 if (IdentifierInfoLookup *External
3995 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003996 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003997 do {
3998 StringRef Name = Iter->Next();
3999 if (Name.empty())
4000 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00004001
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004002 Consumer.FoundName(Name);
4003 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00004004 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004005 }
4006
Richard Smith0f4b5be2012-06-08 21:35:42 +00004007 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004008
Douglas Gregoraaf87162010-04-14 20:04:41 +00004009 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004010 if (Consumer.empty()) {
4011 // If this was an unqualified lookup, note that no correction was found.
4012 if (IsUnqualifiedLookup)
4013 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004014
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004015 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004016 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004017
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004018 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4019 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004020 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004021 if (ED > 0 && Typo->getName().size() / ED < 3) {
4022 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00004023 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004024 (void)UnqualifiedTyposCorrected[Typo];
4025
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004026 return TypoCorrection();
4027 }
4028
Douglas Gregor01798682012-03-26 16:54:18 +00004029 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4030 // to search those namespaces.
4031 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004032 // Load any externally-known namespaces.
4033 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004034 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004035 LoadedExternalKnownNamespaces = true;
4036 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4037 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4038 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4039 }
4040
Nick Lewycky01a41142013-01-26 00:35:08 +00004041 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004042 KNI = KnownNamespaces.begin(),
4043 KNIEnd = KnownNamespaces.end();
4044 KNI != KNIEnd; ++KNI)
4045 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004046 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004047
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004048 // Weed out any names that could not be found by name lookup or, if a
4049 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004050 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004051 LookupResult TmpRes(*this, TypoName, LookupKind);
4052 TmpRes.suppressDiagnostics();
4053 while (!Consumer.empty()) {
4054 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
4055 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004056 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4057 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004058 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004059 // If we only want nested name specifier corrections, ignore potential
4060 // corrections that have a different base identifier from the typo.
4061 if (AllowOnlyNNSChanges &&
4062 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4063 TypoCorrectionConsumer::result_iterator Prev = I;
4064 ++I;
4065 DI->second.erase(Prev);
4066 continue;
4067 }
4068
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004069 // If the item already has been looked up or is a keyword, keep it.
4070 // If a validator callback object was given, drop the correction
4071 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004072 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00004073 for (TypoResultList::iterator RI = I->second.begin();
4074 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004075 TypoResultList::iterator Prev = RI;
4076 ++RI;
4077 if (Prev->isResolved()) {
4078 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00004079 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004080 else
4081 Viable = true;
4082 }
4083 }
4084 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004085 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004086 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004087 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004088 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004089 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00004090 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004091 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004092
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004093 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004094 TypoCorrection &Candidate = I->second.front();
4095 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004096 DeclContext *TempMemberContext = MemberContext;
4097 CXXScopeSpec *TempSS = SS;
4098retry_lookup:
4099 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4100 TempMemberContext, EnteringContext,
4101 CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004102
4103 switch (TmpRes.getResultKind()) {
4104 case LookupResult::NotFound:
4105 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004106 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004107 if (TempSS) {
4108 // Immediately retry the lookup without the given CXXScopeSpec
4109 TempSS = NULL;
4110 Candidate.WillReplaceSpecifier(true);
4111 goto retry_lookup;
4112 }
4113 if (TempMemberContext) {
4114 if (SS && !TempSS)
4115 TempSS = SS;
4116 TempMemberContext = NULL;
4117 goto retry_lookup;
4118 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004119 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004120 // We didn't find this name in our scope, or didn't like what we found;
4121 // ignore it.
4122 {
4123 TypoCorrectionConsumer::result_iterator Next = I;
4124 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004125 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004126 I = Next;
4127 }
4128 break;
4129
4130 case LookupResult::Ambiguous:
4131 // We don't deal with ambiguities.
4132 return TypoCorrection();
4133
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004134 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004135 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004136 // Store all of the Decls for overloaded symbols
4137 for (LookupResult::iterator TRD = TmpRes.begin(),
4138 TRDEnd = TmpRes.end();
4139 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004140 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004141 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004142 if (!isCandidateViable(CCC, Candidate)) {
4143 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004144 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004145 }
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004146 break;
4147 }
4148
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004149 case LookupResult::Found: {
4150 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004151 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004152 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004153 if (!isCandidateViable(CCC, Candidate)) {
4154 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004155 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004156 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004157 break;
4158 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004159
4160 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004161 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004162
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004163 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004164 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00004165 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004166 // If there are results in the closest possible bucket, stop
4167 break;
4168
4169 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004170 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004171 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004172 for (SmallVector<TypoCorrection,
4173 16>::iterator QRI = QualifiedResults.begin(),
4174 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004175 QRI != QRIEnd; ++QRI) {
4176 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4177 NIEnd = Namespaces.end();
4178 NI != NIEnd; ++NI) {
4179 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004180
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004181 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004182 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004183 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004184
4185 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004186 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004187 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4188
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004189 // Any corrections added below will be validated in subsequent
4190 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004191 switch (TmpRes.getResultKind()) {
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004192 case LookupResult::Found:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004193 case LookupResult::FoundOverloaded: {
4194 TypoCorrection TC(*QRI);
4195 TC.setCorrectionSpecifier(NI->NameSpecifier);
4196 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004197 TC.setCallbackDistance(0); // Reset the callback distance
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004198 for (LookupResult::iterator TRD = TmpRes.begin(),
4199 TRDEnd = TmpRes.end();
4200 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004201 TC.addCorrectionDecl(*TRD);
4202 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004203 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004204 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004205 case LookupResult::NotFound:
4206 case LookupResult::NotFoundInCurrentInstantiation:
4207 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004208 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004209 break;
4210 }
4211 }
4212 }
4213 }
4214
4215 QualifiedResults.clear();
4216 }
4217
4218 // No corrections remain...
4219 if (Consumer.empty()) return TypoCorrection();
4220
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004221 TypoResultsMap &BestResults = Consumer.getBestResults();
4222 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004223
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004224 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004225 // If this was an unqualified lookup and we believe the callback
4226 // object wouldn't have filtered out possible corrections, note
4227 // that no correction was found.
4228 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004229 (void)UnqualifiedTyposCorrected[Typo];
4230
4231 return TypoCorrection();
4232 }
4233
Douglas Gregore24b5752010-10-14 20:34:08 +00004234 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004235 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004236 const TypoResultList &CorrectionList = BestResults.begin()->second;
4237 const TypoCorrection &Result = CorrectionList.front();
4238 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004239
Douglas Gregor53e4b552010-10-26 17:18:00 +00004240 // Don't correct to a keyword that's the same as the typo; the keyword
4241 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004242 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4243
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004244 // Record the correction for unqualified lookup.
4245 if (IsUnqualifiedLookup)
4246 UnqualifiedTyposCorrected[Typo] = Result;
4247
David Blaikie6952c012012-10-12 20:00:44 +00004248 TypoCorrection TC = Result;
4249 TC.setCorrectionRange(SS, TypoName);
4250 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004251 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004252 else if (BestResults.size() > 1
4253 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4254 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4255 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4256 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004257 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004258 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004259 // Prefer 'super' when we're completing in a message-receiver
4260 // context.
4261
4262 // Don't correct to a keyword that's the same as the typo; the keyword
4263 // wasn't actually in scope.
4264 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004265
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004266 // Record the correction for unqualified lookup.
4267 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004268 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004269
David Blaikie6952c012012-10-12 20:00:44 +00004270 TypoCorrection TC = BestResults["super"].front();
4271 TC.setCorrectionRange(SS, TypoName);
4272 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004273 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004274
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004275 // If this was an unqualified lookup and we believe the callback object did
4276 // not filter out possible corrections, note that no correction was found.
4277 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004278 (void)UnqualifiedTyposCorrected[Typo];
4279
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004280 return TypoCorrection();
4281}
4282
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004283void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4284 if (!CDecl) return;
4285
4286 if (isKeyword())
4287 CorrectionDecls.clear();
4288
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004289 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004290
4291 if (!CorrectionName)
4292 CorrectionName = CDecl->getDeclName();
4293}
4294
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004295std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4296 if (CorrectionNameSpec) {
4297 std::string tmpBuffer;
4298 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4299 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikie17828ca2013-05-14 21:04:00 +00004300 PrefixOStream << CorrectionName;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004301 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004302 }
4303
4304 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004305}
Kaelyn Uhrain20a7cf42013-04-03 16:59:49 +00004306
4307bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4308 if (!candidate.isResolved())
4309 return true;
4310
4311 if (candidate.isKeyword())
4312 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4313 WantRemainingKeywords || WantObjCSuper;
4314
4315 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4316 CDeclEnd = candidate.end();
4317 CDecl != CDeclEnd; ++CDecl) {
4318 if (!isa<TypeDecl>(*CDecl))
4319 return true;
4320 }
4321
4322 return WantTypeSpecifiers;
4323}
Kaelyn Uhrain761695f2013-07-08 23:13:39 +00004324
4325FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4326 bool HasExplicitTemplateArgs)
4327 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
4328 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4329 WantRemainingKeywords = false;
4330}
4331
4332bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4333 if (!candidate.getCorrectionDecl())
4334 return candidate.isKeyword();
4335
4336 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4337 DIEnd = candidate.end();
4338 DI != DIEnd; ++DI) {
4339 FunctionDecl *FD = 0;
4340 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4341 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4342 FD = FTD->getTemplatedDecl();
4343 if (!HasExplicitTemplateArgs && !FD) {
4344 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4345 // If the Decl is neither a function nor a template function,
4346 // determine if it is a pointer or reference to a function. If so,
4347 // check against the number of arguments expected for the pointee.
4348 QualType ValType = cast<ValueDecl>(ND)->getType();
4349 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4350 ValType = ValType->getPointeeType();
4351 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4352 if (FPT->getNumArgs() == NumArgs)
4353 return true;
4354 }
4355 }
4356 if (FD && FD->getNumParams() >= NumArgs &&
4357 FD->getMinRequiredArguments() <= NumArgs)
4358 return true;
4359 }
4360 return false;
4361}