blob: 2b80b97728134513f24b64abfa43def03eb35292 [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.
Ted Kremenekf0d58612013-10-08 17:08:03 +0000105 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCalld7be78a2009-11-10 07:01:13 +0000106 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000107
John McCalld7be78a2009-11-10 07:01:13 +0000108 for (; S; S = S->getParent()) {
Nick Lewycky65daef12012-03-13 04:12:34 +0000109 // C++ [namespace.udir]p1:
110 // A using-directive shall not appear in class scope, but may
111 // appear in namespace scope or in block scope.
Ted Kremenekf0d58612013-10-08 17:08:03 +0000112 DeclContext *Ctx = S->getEntity();
Nick Lewycky65daef12012-03-13 04:12:34 +0000113 if (Ctx && Ctx->isFileContext()) {
114 visit(Ctx, Ctx);
115 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
John McCalld7be78a2009-11-10 07:01:13 +0000116 Scope::udir_iterator I = S->using_directives_begin(),
117 End = S->using_directives_end();
John McCalld7be78a2009-11-10 07:01:13 +0000118 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000119 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000120 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000121 }
122 }
John McCalld7be78a2009-11-10 07:01:13 +0000123
124 // Visits a context and collect all of its using directives
125 // recursively. Treats all using directives as if they were
126 // declared in the context.
127 //
128 // A given context is only every visited once, so it is important
129 // that contexts be visited from the inside out in order to get
130 // the effective DCs right.
131 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
132 if (!visited.insert(DC))
133 return;
134
135 addUsingDirectives(DC, EffectiveDC);
136 }
137
138 // Visits a using directive and collects all of its using
139 // directives recursively. Treats all using directives as if they
140 // were declared in the effective DC.
141 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
142 DeclContext *NS = UD->getNominatedNamespace();
143 if (!visited.insert(NS))
144 return;
145
146 addUsingDirective(UD, EffectiveDC);
147 addUsingDirectives(NS, EffectiveDC);
148 }
149
150 // Adds all the using directives in a context (and those nominated
151 // by its using directives, transitively) as if they appeared in
152 // the given effective context.
153 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000154 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-11-10 07:01:13 +0000155 while (true) {
156 DeclContext::udir_iterator I, End;
157 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
158 UsingDirectiveDecl *UD = *I;
159 DeclContext *NS = UD->getNominatedNamespace();
160 if (visited.insert(NS)) {
161 addUsingDirective(UD, EffectiveDC);
162 queue.push_back(NS);
163 }
164 }
165
166 if (queue.empty())
167 return;
168
Robert Wilhelm344472e2013-08-23 16:11:15 +0000169 DC = queue.pop_back_val();
John McCalld7be78a2009-11-10 07:01:13 +0000170 }
171 }
172
173 // Add a using directive as if it had been declared in the given
174 // context. This helps implement C++ [namespace.udir]p3:
175 // The using-directive is transitive: if a scope contains a
176 // using-directive that nominates a second namespace that itself
177 // contains using-directives, the effect is as if the
178 // using-directives from the second namespace also appeared in
179 // the first.
180 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
181 // Find the common ancestor between the effective context and
182 // the nominated namespace.
183 DeclContext *Common = UD->getNominatedNamespace();
184 while (!Common->Encloses(EffectiveDC))
185 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000186 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000187
John McCalld7be78a2009-11-10 07:01:13 +0000188 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
189 }
190
191 void done() {
192 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
193 }
194
John McCalld7be78a2009-11-10 07:01:13 +0000195 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000196
John McCalld7be78a2009-11-10 07:01:13 +0000197 const_iterator begin() const { return list.begin(); }
198 const_iterator end() const { return list.end(); }
199
200 std::pair<const_iterator,const_iterator>
201 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000202 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000203 UnqualUsingEntry::Comparator());
204 }
205 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000206}
207
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000208// Retrieve the set of identifier namespaces that correspond to a
209// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000210static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
211 bool CPlusPlus,
212 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000213 unsigned IDNS = 0;
214 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000215 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000216 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000217 case Sema::LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +0000218 case Sema::LookupLocalFriendName:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000219 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000220 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000221 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000222 if (Redeclaration)
223 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000224 }
Richard Smitha41c97a2013-09-20 01:15:31 +0000225 if (Redeclaration)
226 IDNS |= Decl::IDNS_LocalExtern;
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();
Reid Kleckneref072032013-08-27 23:08:25 +0000732 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
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) {
Ted Kremenekf0d58612013-10-08 17:08:03 +0000777 if (DeclContext *Ctx = 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) {
Ted Kremenekf0d58612013-10-08 17:08:03 +0000790 DeclContext *DC = S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +0000791 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()) {
Ted Kremenekf0d58612013-10-08 17:08:03 +0000795 Lexical = 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
Richard Smitha41c97a2013-09-20 01:15:31 +0000851namespace {
852/// An RAII object to specify that we want to find block scope extern
853/// declarations.
854struct FindLocalExternScope {
855 FindLocalExternScope(LookupResult &R)
856 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
857 Decl::IDNS_LocalExtern) {
858 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
859 }
860 void restore() {
861 R.setFindLocalExtern(OldFindLocalExtern);
862 }
863 ~FindLocalExternScope() {
864 restore();
865 }
866 LookupResult &R;
867 bool OldFindLocalExtern;
868};
869}
870
John McCalla24dc2e2009-11-17 02:14:36 +0000871bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000872 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000873
874 DeclarationName Name = R.getLookupName();
Richard Smithdd9459f2013-08-13 18:18:50 +0000875 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCalla24dc2e2009-11-17 02:14:36 +0000876
Douglas Gregora376d102010-07-02 21:50:04 +0000877 // If this is the name of an implicitly-declared special member function,
878 // go through the scope stack to implicitly declare
879 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
880 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekf0d58612013-10-08 17:08:03 +0000881 if (DeclContext *DC = PreS->getEntity())
Douglas Gregora376d102010-07-02 21:50:04 +0000882 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
883 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000884
Douglas Gregora376d102010-07-02 21:50:04 +0000885 // Implicitly declare member functions with the name we're looking for, if in
886 // fact we are in a scope where it matters.
887
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000888 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000889 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000890 I = IdResolver.begin(Name),
891 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000892
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000893 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000894 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000895 // ...During unqualified name lookup (3.4.1), the names appear as if
896 // they were declared in the nearest enclosing namespace which contains
897 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000898 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000899 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000900 //
901 // For example:
902 // namespace A { int i; }
903 // void foo() {
904 // int i;
905 // {
906 // using namespace A;
907 // ++i; // finds local 'i', A::i appears at global scope
908 // }
909 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000910 //
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000911 UnqualUsingDirectiveSet UDirs;
912 bool VisitedUsingDirectives = false;
Richard Smithdd9459f2013-08-13 18:18:50 +0000913 bool LeftStartingScope = false;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000914 DeclContext *OutsideOfTemplateParamDC = 0;
Richard Smitha41c97a2013-09-20 01:15:31 +0000915
916 // When performing a scope lookup, we want to find local extern decls.
917 FindLocalExternScope FindLocals(R);
918
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000919 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekf0d58612013-10-08 17:08:03 +0000920 DeclContext *Ctx = S->getEntity();
Douglas Gregord2235f62010-05-20 20:58:56 +0000921
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000922 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000923 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000924 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000925 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smithdd9459f2013-08-13 18:18:50 +0000926 if (NameKind == LookupRedeclarationWithLinkage) {
927 // Determine whether this (or a previous) declaration is
928 // out-of-scope.
929 if (!LeftStartingScope && !Initial->isDeclScope(*I))
930 LeftStartingScope = true;
931
932 // If we found something outside of our starting scope that
933 // does not have linkage, skip it.
934 if (LeftStartingScope && !((*I)->hasLinkage())) {
935 R.setShadowed();
936 continue;
937 }
938 }
939
John McCallf36e02d2009-10-09 21:13:30 +0000940 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000941 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000942 }
943 }
John McCallf36e02d2009-10-09 21:13:30 +0000944 if (Found) {
945 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000946 if (S->isClassScope())
947 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
948 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000949 return true;
950 }
951
Richard Smithdd9459f2013-08-13 18:18:50 +0000952 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith4e9686b2013-08-09 04:35:01 +0000953 // C++11 [class.friend]p11:
954 // If a friend declaration appears in a local class and the name
955 // specified is an unqualified name, a prior declaration is
956 // looked up without considering scopes that are outside the
957 // innermost enclosing non-class scope.
958 return false;
959 }
960
Douglas Gregor711be1e2010-03-15 14:33:29 +0000961 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
962 S->getParent() && !S->getParent()->isTemplateParamScope()) {
963 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000964 // found nothing, so look into the contexts between the
Douglas Gregor711be1e2010-03-15 14:33:29 +0000965 // lexical and semantic declaration contexts returned by
966 // findOuterContext(). This implements the name lookup behavior
967 // of C++ [temp.local]p8.
968 Ctx = OutsideOfTemplateParamDC;
969 OutsideOfTemplateParamDC = 0;
970 }
971
972 if (Ctx) {
973 DeclContext *OuterCtx;
974 bool SearchAfterTemplateScope;
975 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
976 if (SearchAfterTemplateScope)
977 OutsideOfTemplateParamDC = OuterCtx;
978
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000979 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000980 // We do not directly look into transparent contexts, since
981 // those entities will be found in the nearest enclosing
982 // non-transparent context.
983 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000984 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000985
986 // We do not look directly into function or method contexts,
987 // since all of the local variables and parameters of the
988 // function/method are present within the Scope.
989 if (Ctx->isFunctionOrMethod()) {
990 // If we have an Objective-C instance method, look for ivars
991 // in the corresponding interface.
992 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
993 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
994 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
995 ObjCInterfaceDecl *ClassDeclared;
996 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000997 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000998 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000999 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1000 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +00001001 R.resolveKind();
1002 return true;
1003 }
1004 }
1005 }
1006 }
1007
1008 continue;
1009 }
1010
Douglas Gregor6bed88e2013-03-27 12:51:49 +00001011 // If this is a file context, we need to perform unqualified name
1012 // lookup considering using directives.
1013 if (Ctx->isFileContext()) {
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001014 // If we haven't handled using directives yet, do so now.
1015 if (!VisitedUsingDirectives) {
1016 // Add using directives from this context up to the top level.
Douglas Gregor34366202013-04-09 01:49:26 +00001017 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1018 if (UCtx->isTransparentContext())
1019 continue;
1020
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001021 UDirs.visit(UCtx, UCtx);
Douglas Gregor34366202013-04-09 01:49:26 +00001022 }
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001023
1024 // Find the innermost file scope, so we can add using directives
1025 // from local scopes.
1026 Scope *InnermostFileScope = S;
1027 while (InnermostFileScope &&
1028 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1029 InnermostFileScope = InnermostFileScope->getParent();
1030 UDirs.visitScopeChain(Initial, InnermostFileScope);
1031
1032 UDirs.done();
1033
1034 VisitedUsingDirectives = true;
1035 }
Douglas Gregor6bed88e2013-03-27 12:51:49 +00001036
1037 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1038 R.resolveKind();
1039 return true;
1040 }
1041
1042 continue;
1043 }
1044
Douglas Gregore942bbe2009-09-10 16:57:35 +00001045 // Perform qualified name lookup into this context.
1046 // FIXME: In some cases, we know that every name that could be found by
1047 // this qualified name lookup will also be on the identifier chain. For
1048 // example, inside a class without any base classes, we never need to
1049 // perform qualified lookup because all of the members are on top of the
1050 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001051 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +00001052 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +00001053 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001054 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001055 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001056
John McCalld7be78a2009-11-10 07:01:13 +00001057 // Stop if we ran out of scopes.
1058 // FIXME: This really, really shouldn't be happening.
1059 if (!S) return false;
1060
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001061 // If we are looking for members, no need to look into global/namespace scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00001062 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001063 return false;
1064
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001065 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001066 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +00001067 //
Mike Stump390b4cc2009-05-16 07:39:55 +00001068 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1069 // don't build it for each lookup!
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001070 if (!VisitedUsingDirectives) {
1071 UDirs.visitScopeChain(Initial, S);
1072 UDirs.done();
1073 }
Richard Smitha41c97a2013-09-20 01:15:31 +00001074
1075 // If we're not performing redeclaration lookup, do not look for local
1076 // extern declarations outside of a function scope.
1077 if (!R.isForRedeclaration())
1078 FindLocals.restore();
1079
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001080 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001081 // Unqualified name lookup in C++ requires looking into scopes
1082 // that aren't strictly lexical, and therefore we walk through the
1083 // context as well as walking through the scopes.
1084 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001085 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +00001086 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +00001087 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +00001088 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001089 // We found something. Look for anything else in our scope
1090 // with this same name and in an acceptable identifier
1091 // namespace, so that we can construct an overload set if we
1092 // need to.
John McCallf36e02d2009-10-09 21:13:30 +00001093 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +00001094 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001095 }
1096 }
1097
Douglas Gregor00b4b032010-05-14 04:53:42 +00001098 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +00001099 R.resolveKind();
1100 return true;
1101 }
1102
Ted Kremenekf0d58612013-10-08 17:08:03 +00001103 DeclContext *Ctx = S->getEntity();
Douglas Gregor00b4b032010-05-14 04:53:42 +00001104 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1105 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1106 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001107 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001108 // lexical and semantic declaration contexts returned by
1109 // findOuterContext(). This implements the name lookup behavior
1110 // of C++ [temp.local]p8.
1111 Ctx = OutsideOfTemplateParamDC;
1112 OutsideOfTemplateParamDC = 0;
1113 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001114
Douglas Gregor00b4b032010-05-14 04:53:42 +00001115 if (Ctx) {
1116 DeclContext *OuterCtx;
1117 bool SearchAfterTemplateScope;
1118 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1119 if (SearchAfterTemplateScope)
1120 OutsideOfTemplateParamDC = OuterCtx;
1121
1122 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1123 // We do not directly look into transparent contexts, since
1124 // those entities will be found in the nearest enclosing
1125 // non-transparent context.
1126 if (Ctx->isTransparentContext())
1127 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001128
Douglas Gregor00b4b032010-05-14 04:53:42 +00001129 // If we have a context, and it's not a context stashed in the
1130 // template parameter scope for an out-of-line definition, also
1131 // look into that context.
1132 if (!(Found && S && S->isTemplateParamScope())) {
1133 assert(Ctx->isFileContext() &&
1134 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001135
Douglas Gregor00b4b032010-05-14 04:53:42 +00001136 // Look into context considering using-directives.
1137 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1138 Found = true;
1139 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001140
Douglas Gregor00b4b032010-05-14 04:53:42 +00001141 if (Found) {
1142 R.resolveKind();
1143 return true;
1144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001145
Douglas Gregor00b4b032010-05-14 04:53:42 +00001146 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1147 return false;
1148 }
1149 }
1150
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001151 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001152 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001153 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001154
John McCallf36e02d2009-10-09 21:13:30 +00001155 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001156}
1157
Richard Smithb7751002013-07-25 23:08:39 +00001158/// \brief Find the declaration that a class temploid member specialization was
1159/// instantiated from, or the member itself if it is an explicit specialization.
1160static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1161 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1162}
1163
1164/// \brief Find the module in which the given declaration was defined.
1165static Module *getDefiningModule(Decl *Entity) {
1166 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1167 // If this function was instantiated from a template, the defining module is
1168 // the module containing the pattern.
1169 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1170 Entity = Pattern;
1171 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1172 // If it's a class template specialization, find the template or partial
1173 // specialization from which it was instantiated.
1174 if (ClassTemplateSpecializationDecl *SpecRD =
1175 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1176 llvm::PointerUnion<ClassTemplateDecl*,
1177 ClassTemplatePartialSpecializationDecl*> From =
1178 SpecRD->getInstantiatedFrom();
1179 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1180 Entity = FromTemplate->getTemplatedDecl();
1181 else if (From)
1182 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1183 // Otherwise, it's an explicit specialization.
1184 } else if (MemberSpecializationInfo *MSInfo =
1185 RD->getMemberSpecializationInfo())
1186 Entity = getInstantiatedFrom(RD, MSInfo);
1187 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1188 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1189 Entity = getInstantiatedFrom(ED, MSInfo);
1190 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1191 // FIXME: Map from variable template specializations back to the template.
1192 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1193 Entity = getInstantiatedFrom(VD, MSInfo);
1194 }
1195
1196 // Walk up to the containing context. That might also have been instantiated
1197 // from a template.
1198 DeclContext *Context = Entity->getDeclContext();
1199 if (Context->isFileContext())
1200 return Entity->getOwningModule();
1201 return getDefiningModule(cast<Decl>(Context));
1202}
1203
1204llvm::DenseSet<Module*> &Sema::getLookupModules() {
1205 unsigned N = ActiveTemplateInstantiations.size();
1206 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1207 I != N; ++I) {
1208 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1209 if (M && !LookupModulesCache.insert(M).second)
1210 M = 0;
1211 ActiveTemplateInstantiationLookupModules.push_back(M);
1212 }
1213 return LookupModulesCache;
1214}
1215
1216/// \brief Determine whether a declaration is visible to name lookup.
1217///
1218/// This routine determines whether the declaration D is visible in the current
1219/// lookup context, taking into account the current template instantiation
1220/// stack. During template instantiation, a declaration is visible if it is
1221/// visible from a module containing any entity on the template instantiation
1222/// path (by instantiating a template, you allow it to see the declarations that
1223/// your module can see, including those later on in your module).
1224bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1225 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1226 "should not call this: not in slow case");
1227 Module *DeclModule = D->getOwningModule();
1228 assert(DeclModule && "hidden decl not from a module");
1229
1230 // Find the extra places where we need to look.
1231 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1232 if (LookupModules.empty())
1233 return false;
1234
1235 // If our lookup set contains the decl's module, it's visible.
1236 if (LookupModules.count(DeclModule))
1237 return true;
1238
1239 // If the declaration isn't exported, it's not visible in any other module.
1240 if (D->isModulePrivate())
1241 return false;
1242
1243 // Check whether DeclModule is transitively exported to an import of
1244 // the lookup set.
1245 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1246 E = LookupModules.end();
1247 I != E; ++I)
1248 if ((*I)->isModuleVisible(DeclModule))
1249 return true;
1250 return false;
1251}
1252
Douglas Gregor55368912011-12-14 16:03:29 +00001253/// \brief Retrieve the visible declaration corresponding to D, if any.
1254///
1255/// This routine determines whether the declaration D is visible in the current
1256/// module, with the current imports. If not, it checks whether any
1257/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smithb7751002013-07-25 23:08:39 +00001258///
Douglas Gregor55368912011-12-14 16:03:29 +00001259/// \returns D, or a visible previous declaration of D, whichever is more recent
1260/// and visible. If no declaration of D is visible, returns null.
Richard Smithd67679d2013-08-20 20:35:18 +00001261static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1262 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smithb7751002013-07-25 23:08:39 +00001263
Douglas Gregor0782ef22012-01-06 22:05:37 +00001264 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1265 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001266 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Richard Smithd67679d2013-08-20 20:35:18 +00001267 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor0782ef22012-01-06 22:05:37 +00001268 return ND;
1269 }
Douglas Gregor55368912011-12-14 16:03:29 +00001270 }
Richard Smithb7751002013-07-25 23:08:39 +00001271
Douglas Gregor55368912011-12-14 16:03:29 +00001272 return 0;
1273}
1274
Richard Smithd67679d2013-08-20 20:35:18 +00001275NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1276 return findAcceptableDecl(SemaRef, D);
1277}
1278
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001279/// @brief Perform unqualified name lookup starting from a given
1280/// scope.
1281///
1282/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1283/// used to find names within the current scope. For example, 'x' in
1284/// @code
1285/// int x;
1286/// int f() {
1287/// return x; // unqualified name look finds 'x' in the global scope
1288/// }
1289/// @endcode
1290///
1291/// Different lookup criteria can find different names. For example, a
1292/// particular scope can have both a struct and a function of the same
1293/// name, and each can be found by certain lookup criteria. For more
1294/// information about lookup criteria, see the documentation for the
1295/// class LookupCriteria.
1296///
1297/// @param S The scope from which unqualified name lookup will
1298/// begin. If the lookup criteria permits, name lookup may also search
1299/// in the parent scopes.
1300///
James Dennett8da16872012-06-22 10:32:46 +00001301/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1302/// look up and the lookup kind), and is updated with the results of lookup
1303/// including zero or more declarations and possibly additional information
1304/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001305///
James Dennett8da16872012-06-22 10:32:46 +00001306/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001307bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1308 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001309 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001310
John McCalla24dc2e2009-11-17 02:14:36 +00001311 LookupNameKind NameKind = R.getLookupKind();
1312
David Blaikie4e4d0842012-03-11 07:00:24 +00001313 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001314 // Unqualified name lookup in C/Objective-C is purely lexical, so
1315 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001316 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001317 // Find the nearest non-transparent declaration scope.
1318 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +00001319 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001320 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001321 }
1322
Richard Smitha41c97a2013-09-20 01:15:31 +00001323 // When performing a scope lookup, we want to find local extern decls.
1324 FindLocalExternScope FindLocals(R);
1325
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001326 // Scan up the scope chain looking for a decl that matches this
1327 // identifier that is in the appropriate namespace. This search
1328 // should not take long, as shadowing of names is uncommon, and
1329 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001330 bool LeftStartingScope = false;
1331
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001332 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001333 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001334 I != IEnd; ++I)
Richard Smithb7751002013-07-25 23:08:39 +00001335 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001336 if (NameKind == LookupRedeclarationWithLinkage) {
1337 // Determine whether this (or a previous) declaration is
1338 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001339 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001340 LeftStartingScope = true;
1341
1342 // If we found something outside of our starting scope that
1343 // does not have linkage, skip it.
Richard Smithdd9459f2013-08-13 18:18:50 +00001344 if (LeftStartingScope && !((*I)->hasLinkage())) {
1345 R.setShadowed();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001346 continue;
Richard Smithdd9459f2013-08-13 18:18:50 +00001347 }
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001348 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001349 else if (NameKind == LookupObjCImplicitSelfParam &&
1350 !isa<ImplicitParamDecl>(*I))
1351 continue;
Richard Smithb7751002013-07-25 23:08:39 +00001352
Douglas Gregor55368912011-12-14 16:03:29 +00001353 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001354
Douglas Gregor7a537402012-01-03 23:26:26 +00001355 // Check whether there are any other declarations with the same name
1356 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001357 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001358 // Find the scope in which this declaration was declared (if it
1359 // actually exists in a Scope).
1360 while (S && !S->isDeclScope(D))
1361 S = S->getParent();
1362
1363 // If the scope containing the declaration is the translation unit,
1364 // then we'll need to perform our checks based on the matching
1365 // DeclContexts rather than matching scopes.
1366 if (S && isNamespaceOrTranslationUnitScope(S))
1367 S = 0;
1368
1369 // Compute the DeclContext, if we need it.
1370 DeclContext *DC = 0;
1371 if (!S)
1372 DC = (*I)->getDeclContext()->getRedeclContext();
1373
Douglas Gregorda795b42012-01-04 16:44:10 +00001374 IdentifierResolver::iterator LastI = I;
1375 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001376 if (S) {
1377 // Match based on scope.
1378 if (!S->isDeclScope(*LastI))
1379 break;
1380 } else {
1381 // Match based on DeclContext.
1382 DeclContext *LastDC
1383 = (*LastI)->getDeclContext()->getRedeclContext();
1384 if (!LastDC->Equals(DC))
1385 break;
1386 }
Richard Smithb7751002013-07-25 23:08:39 +00001387
1388 // If the declaration is in the right namespace and visible, add it.
1389 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1390 R.addDecl(LastD);
Douglas Gregorda795b42012-01-04 16:44:10 +00001391 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001392
Douglas Gregorda795b42012-01-04 16:44:10 +00001393 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001394 }
Richard Smitha41c97a2013-09-20 01:15:31 +00001395
John McCallf36e02d2009-10-09 21:13:30 +00001396 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001397 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001398 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001399 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001400 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001401 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001402 }
1403
1404 // If we didn't find a use of this identifier, and if the identifier
1405 // corresponds to a compiler builtin, create the decl object for the builtin
1406 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001407 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1408 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001409
Axel Naumannf8291a12011-02-24 16:47:47 +00001410 // If we didn't find a use of this identifier, the ExternalSource
1411 // may be able to handle the situation.
1412 // Note: some lookup failures are expected!
1413 // See e.g. R.isForRedeclaration().
1414 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001415}
1416
John McCall6e247262009-10-10 05:48:19 +00001417/// @brief Perform qualified name lookup in the namespaces nominated by
1418/// using directives by the given context.
1419///
1420/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001421/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001422/// (where X is the global namespace), let S be the set of all
1423/// declarations of m in X and in the transitive closure of all
1424/// namespaces nominated by using-directives in X and its used
1425/// namespaces, except that using-directives are ignored in any
1426/// namespace, including X, directly containing one or more
1427/// declarations of m. No namespace is searched more than once in
1428/// the lookup of a name. If S is the empty set, the program is
1429/// ill-formed. Otherwise, if S has exactly one member, or if the
1430/// context of the reference is a using-declaration
1431/// (namespace.udecl), S is the required set of declarations of
1432/// m. Otherwise if the use of m is not one that allows a unique
1433/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001434///
John McCall6e247262009-10-10 05:48:19 +00001435/// C++98 [namespace.qual]p5:
1436/// During the lookup of a qualified namespace member name, if the
1437/// lookup finds more than one declaration of the member, and if one
1438/// declaration introduces a class name or enumeration name and the
1439/// other declarations either introduce the same object, the same
1440/// enumerator or a set of functions, the non-type name hides the
1441/// class or enumeration name if and only if the declarations are
1442/// from the same namespace; otherwise (the declarations are from
1443/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001444static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001445 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001446 assert(StartDC->isFileContext() && "start context is not a file context");
1447
1448 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1449 DeclContext::udir_iterator E = StartDC->using_directives_end();
1450
1451 if (I == E) return false;
1452
1453 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001454 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001455 Visited.insert(StartDC);
1456
1457 // We have not yet looked into these namespaces, much less added
1458 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001459 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001460
1461 // We have already looked into the initial namespace; seed the queue
1462 // with its using-children.
1463 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001464 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001465 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001466 Queue.push_back(ND);
1467 }
1468
1469 // The easiest way to implement the restriction in [namespace.qual]p5
1470 // is to check whether any of the individual results found a tag
1471 // and, if so, to declare an ambiguity if the final result is not
1472 // a tag.
1473 bool FoundTag = false;
1474 bool FoundNonTag = false;
1475
John McCall7d384dd2009-11-18 07:57:50 +00001476 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001477
1478 bool Found = false;
1479 while (!Queue.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00001480 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6e247262009-10-10 05:48:19 +00001481
1482 // We go through some convolutions here to avoid copying results
1483 // between LookupResults.
1484 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001485 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001486 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001487
1488 if (FoundDirect) {
1489 // First do any local hiding.
1490 DirectR.resolveKind();
1491
1492 // If the local result is a tag, remember that.
1493 if (DirectR.isSingleTagDecl())
1494 FoundTag = true;
1495 else
1496 FoundNonTag = true;
1497
1498 // Append the local results to the total results if necessary.
1499 if (UseLocal) {
1500 R.addAllDecls(LocalR);
1501 LocalR.clear();
1502 }
1503 }
1504
1505 // If we find names in this namespace, ignore its using directives.
1506 if (FoundDirect) {
1507 Found = true;
1508 continue;
1509 }
1510
1511 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1512 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001513 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001514 Queue.push_back(Nom);
1515 }
1516 }
1517
1518 if (Found) {
1519 if (FoundTag && FoundNonTag)
1520 R.setAmbiguousQualifiedTagHiding();
1521 else
1522 R.resolveKind();
1523 }
1524
1525 return Found;
1526}
1527
Douglas Gregor8071e422010-08-15 06:18:01 +00001528/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001529static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001530 CXXBasePath &Path,
1531 void *Name) {
1532 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001533
Douglas Gregor8071e422010-08-15 06:18:01 +00001534 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1535 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001536 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001537}
1538
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001539/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001540/// static members, nested types, and enumerators.
1541template<typename InputIterator>
1542static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1543 Decl *D = (*First)->getUnderlyingDecl();
1544 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1545 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001547 if (isa<CXXMethodDecl>(D)) {
1548 // Determine whether all of the methods are static.
1549 bool AllMethodsAreStatic = true;
1550 for(; First != Last; ++First) {
1551 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001552
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001553 if (!isa<CXXMethodDecl>(D)) {
1554 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1555 break;
1556 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001557
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001558 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1559 AllMethodsAreStatic = false;
1560 break;
1561 }
1562 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001563
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001564 if (AllMethodsAreStatic)
1565 return true;
1566 }
1567
1568 return false;
1569}
1570
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001571/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001572///
1573/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1574/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001575/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001576///
1577/// Different lookup criteria can find different names. For example, a
1578/// particular scope can have both a struct and a function of the same
1579/// name, and each can be found by certain lookup criteria. For more
1580/// information about lookup criteria, see the documentation for the
1581/// class LookupCriteria.
1582///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001583/// \param R captures both the lookup criteria and any lookup results found.
1584///
1585/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001586/// search. If the lookup criteria permits, name lookup may also search
1587/// in the parent contexts or (for C++ classes) base classes.
1588///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001589/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001590/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001591///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001592/// \returns true if lookup succeeded, false if it failed.
1593bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1594 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001595 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001596
John McCalla24dc2e2009-11-17 02:14:36 +00001597 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001598 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001600 // Make sure that the declaration context is complete.
1601 assert((!isa<TagDecl>(LookupCtx) ||
1602 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001603 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001604 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001605 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001607 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001608 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001609 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001610 if (isa<CXXRecordDecl>(LookupCtx))
1611 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001612 return true;
1613 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001614
John McCall6e247262009-10-10 05:48:19 +00001615 // Don't descend into implied contexts for redeclarations.
1616 // C++98 [namespace.qual]p6:
1617 // In a declaration for a namespace member in which the
1618 // declarator-id is a qualified-id, given that the qualified-id
1619 // for the namespace member has the form
1620 // nested-name-specifier unqualified-id
1621 // the unqualified-id shall name a member of the namespace
1622 // designated by the nested-name-specifier.
1623 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001624 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001625 return false;
1626
John McCalla24dc2e2009-11-17 02:14:36 +00001627 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001628 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001629 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001630
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001631 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001632 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001633 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001634 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001635 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001636
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001637 // If we're performing qualified name lookup into a dependent class,
1638 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001639 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001640 // template instantiation time (at which point all bases will be available)
1641 // or we have to fail.
1642 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1643 LookupRec->hasAnyDependentBases()) {
1644 R.setNotFoundInCurrentInstantiation();
1645 return false;
1646 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001647
Douglas Gregor7176fff2009-01-15 00:26:24 +00001648 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001649 CXXBasePaths Paths;
1650 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001651
1652 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001653 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001654 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001655 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001656 case LookupOrdinaryName:
1657 case LookupMemberName:
1658 case LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +00001659 case LookupLocalFriendName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001660 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1661 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001662
Douglas Gregora8f32e02009-10-06 17:59:45 +00001663 case LookupTagName:
1664 BaseCallback = &CXXRecordDecl::FindTagMember;
1665 break;
John McCall9f54ad42009-12-10 09:41:52 +00001666
Douglas Gregor8071e422010-08-15 06:18:01 +00001667 case LookupAnyName:
1668 BaseCallback = &LookupAnyMember;
1669 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670
John McCall9f54ad42009-12-10 09:41:52 +00001671 case LookupUsingDeclName:
1672 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001673
Douglas Gregora8f32e02009-10-06 17:59:45 +00001674 case LookupOperatorName:
1675 case LookupNamespaceName:
1676 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001677 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001678 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001679 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680
Douglas Gregora8f32e02009-10-06 17:59:45 +00001681 case LookupNestedNameSpecifierName:
1682 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1683 break;
1684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001685
John McCalla24dc2e2009-11-17 02:14:36 +00001686 if (!LookupRec->lookupInBases(BaseCallback,
1687 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001688 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001689
John McCall92f88312010-01-23 00:46:32 +00001690 R.setNamingClass(LookupRec);
1691
Douglas Gregor7176fff2009-01-15 00:26:24 +00001692 // C++ [class.member.lookup]p2:
1693 // [...] If the resulting set of declarations are not all from
1694 // sub-objects of the same type, or the set has a nonstatic member
1695 // and includes members from distinct sub-objects, there is an
1696 // ambiguity and the program is ill-formed. Otherwise that set is
1697 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001698 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001699 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001700 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001701
Douglas Gregora8f32e02009-10-06 17:59:45 +00001702 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001703 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001704 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001705
John McCall46460a62010-01-20 21:53:11 +00001706 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1707 // across all paths.
1708 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001709
Douglas Gregor7176fff2009-01-15 00:26:24 +00001710 // Determine whether we're looking at a distinct sub-object or not.
1711 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001712 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001713 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1714 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001715 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001716 }
1717
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001718 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001719 != Context.getCanonicalType(PathElement.Base->getType())) {
1720 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001721 // different types. If the declaration sets aren't the same, this
1722 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001723 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001724 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001725 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1726 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001727
David Blaikie3bc93e32012-12-19 00:45:41 +00001728 while (FirstD != FirstPath->Decls.end() &&
1729 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001730 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1731 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1732 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001733
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001734 ++FirstD;
1735 ++CurrentD;
1736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001737
David Blaikie3bc93e32012-12-19 00:45:41 +00001738 if (FirstD == FirstPath->Decls.end() &&
1739 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001740 continue;
1741 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001742
John McCallf36e02d2009-10-09 21:13:30 +00001743 R.setAmbiguousBaseSubobjectTypes(Paths);
1744 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001745 }
1746
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001747 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001748 // We have a different subobject of the same type.
1749
1750 // C++ [class.member.lookup]p5:
1751 // A static member, a nested type or an enumerator defined in
1752 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001753 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001754 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001755 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001756
Douglas Gregor7176fff2009-01-15 00:26:24 +00001757 // We have found a nonstatic member name in multiple, distinct
1758 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001759 R.setAmbiguousBaseSubobjects(Paths);
1760 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001761 }
1762 }
1763
1764 // Lookup in a base class succeeded; return these results.
1765
David Blaikie3bc93e32012-12-19 00:45:41 +00001766 DeclContext::lookup_result DR = Paths.front().Decls;
1767 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001768 NamedDecl *D = *I;
1769 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1770 D->getAccess());
1771 R.addDecl(D, AS);
1772 }
John McCallf36e02d2009-10-09 21:13:30 +00001773 R.resolveKind();
1774 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001775}
1776
1777/// @brief Performs name lookup for a name that was parsed in the
1778/// source code, and may contain a C++ scope specifier.
1779///
1780/// This routine is a convenience routine meant to be called from
1781/// contexts that receive a name and an optional C++ scope specifier
1782/// (e.g., "N::M::x"). It will then perform either qualified or
1783/// unqualified name lookup (with LookupQualifiedName or LookupName,
1784/// respectively) on the given name and return those results.
1785///
1786/// @param S The scope from which unqualified name lookup will
1787/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001788///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001789/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001790///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001791/// @param EnteringContext Indicates whether we are going to enter the
1792/// context of the scope-specifier SS (if present).
1793///
John McCallf36e02d2009-10-09 21:13:30 +00001794/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001795bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001796 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001797 if (SS && SS->isInvalid()) {
1798 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001799 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001800 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001801 }
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Douglas Gregor495c35d2009-08-25 22:51:20 +00001803 if (SS && SS->isSet()) {
1804 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001805 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001806 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001807 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001808 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001809
John McCalla24dc2e2009-11-17 02:14:36 +00001810 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001811 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001812 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001813
Douglas Gregor495c35d2009-08-25 22:51:20 +00001814 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001815 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001816 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001817 R.setNotFoundInCurrentInstantiation();
1818 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001819 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001820 }
1821
Mike Stump1eb44332009-09-09 15:08:12 +00001822 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001823 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001824}
1825
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001826
James Dennett16ae9de2012-06-22 10:16:05 +00001827/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001828/// from name lookup.
1829///
James Dennett16ae9de2012-06-22 10:16:05 +00001830/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001831void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001832 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1833
John McCalla24dc2e2009-11-17 02:14:36 +00001834 DeclarationName Name = Result.getLookupName();
1835 SourceLocation NameLoc = Result.getNameLoc();
1836 SourceRange LookupRange = Result.getContextRange();
1837
John McCall6e247262009-10-10 05:48:19 +00001838 switch (Result.getAmbiguityKind()) {
1839 case LookupResult::AmbiguousBaseSubobjects: {
1840 CXXBasePaths *Paths = Result.getBasePaths();
1841 QualType SubobjectType = Paths->front().back().Base->getType();
1842 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1843 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1844 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001845
David Blaikie3bc93e32012-12-19 00:45:41 +00001846 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001847 while (isa<CXXMethodDecl>(*Found) &&
1848 cast<CXXMethodDecl>(*Found)->isStatic())
1849 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001850
John McCall6e247262009-10-10 05:48:19 +00001851 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001852 break;
John McCall6e247262009-10-10 05:48:19 +00001853 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001854
John McCall6e247262009-10-10 05:48:19 +00001855 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001856 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1857 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001858
John McCall6e247262009-10-10 05:48:19 +00001859 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001860 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001861 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1862 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001863 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001864 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001865 if (DeclsPrinted.insert(D).second)
1866 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1867 }
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001868 break;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001869 }
1870
John McCall6e247262009-10-10 05:48:19 +00001871 case LookupResult::AmbiguousTagHiding: {
1872 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001873
John McCall6e247262009-10-10 05:48:19 +00001874 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1875
1876 LookupResult::iterator DI, DE = Result.end();
1877 for (DI = Result.begin(); DI != DE; ++DI)
1878 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1879 TagDecls.insert(TD);
1880 Diag(TD->getLocation(), diag::note_hidden_tag);
1881 }
1882
1883 for (DI = Result.begin(); DI != DE; ++DI)
1884 if (!isa<TagDecl>(*DI))
1885 Diag((*DI)->getLocation(), diag::note_hiding_object);
1886
1887 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001888 LookupResult::Filter F = Result.makeFilter();
1889 while (F.hasNext()) {
1890 if (TagDecls.count(F.next()))
1891 F.erase();
1892 }
1893 F.done();
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001894 break;
John McCall6e247262009-10-10 05:48:19 +00001895 }
1896
1897 case LookupResult::AmbiguousReference: {
1898 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001899
John McCall6e247262009-10-10 05:48:19 +00001900 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1901 for (; DI != DE; ++DI)
1902 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001903 break;
John McCall6e247262009-10-10 05:48:19 +00001904 }
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001905 }
Douglas Gregor7176fff2009-01-15 00:26:24 +00001906}
Douglas Gregorfa047642009-02-04 00:32:51 +00001907
John McCallc7e04da2010-05-28 18:45:08 +00001908namespace {
1909 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001910 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001911 Sema::AssociatedNamespaceSet &Namespaces,
1912 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001913 : S(S), Namespaces(Namespaces), Classes(Classes),
1914 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001915 }
1916
1917 Sema &S;
1918 Sema::AssociatedNamespaceSet &Namespaces;
1919 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001920 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001921 };
1922}
1923
Mike Stump1eb44332009-09-09 15:08:12 +00001924static void
John McCallc7e04da2010-05-28 18:45:08 +00001925addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001926
Douglas Gregor54022952010-04-30 07:08:38 +00001927static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1928 DeclContext *Ctx) {
1929 // Add the associated namespace for this class.
1930
1931 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1932 // be a locally scoped record.
1933
Sebastian Redl410c4f22010-08-31 20:53:31 +00001934 // We skip out of inline namespaces. The innermost non-inline namespace
1935 // contains all names of all its nested inline namespaces anyway, so we can
1936 // replace the entire inline namespace tree with its root.
1937 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1938 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001939 Ctx = Ctx->getParent();
1940
John McCall6ff07852009-08-07 22:18:02 +00001941 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001942 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001943}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001944
Mike Stump1eb44332009-09-09 15:08:12 +00001945// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001946// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001947static void
John McCallc7e04da2010-05-28 18:45:08 +00001948addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1949 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001950 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001951 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001952 switch (Arg.getKind()) {
1953 case TemplateArgument::Null:
1954 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Douglas Gregor69be8d62009-07-08 07:51:57 +00001956 case TemplateArgument::Type:
1957 // [...] the namespaces and classes associated with the types of the
1958 // template arguments provided for template type parameters (excluding
1959 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001960 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001961 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001962
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001963 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001964 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001965 // [...] the namespaces in which any template template arguments are
1966 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001967 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001968 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001969 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001970 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001971 DeclContext *Ctx = ClassTemplate->getDeclContext();
1972 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001973 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001974 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001975 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001976 }
1977 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001978 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001979
Douglas Gregor788cd062009-11-11 01:00:40 +00001980 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001981 case TemplateArgument::Integral:
1982 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001983 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001984 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001985 // associated namespaces. ]
1986 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Douglas Gregor69be8d62009-07-08 07:51:57 +00001988 case TemplateArgument::Pack:
1989 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1990 PEnd = Arg.pack_end();
1991 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001992 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001993 break;
1994 }
1995}
1996
Douglas Gregorfa047642009-02-04 00:32:51 +00001997// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001998// argument-dependent lookup with an argument of class type
1999// (C++ [basic.lookup.koenig]p2).
2000static void
John McCallc7e04da2010-05-28 18:45:08 +00002001addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2002 CXXRecordDecl *Class) {
2003
2004 // Just silently ignore anything whose name is __va_list_tag.
2005 if (Class->getDeclName() == Result.S.VAListTagName)
2006 return;
2007
Douglas Gregorfa047642009-02-04 00:32:51 +00002008 // C++ [basic.lookup.koenig]p2:
2009 // [...]
2010 // -- If T is a class type (including unions), its associated
2011 // classes are: the class itself; the class of which it is a
2012 // member, if any; and its direct and indirect base
2013 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00002014 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00002015
2016 // Add the class of which it is a member, if any.
2017 DeclContext *Ctx = Class->getDeclContext();
2018 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002019 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002020 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002021 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Douglas Gregorfa047642009-02-04 00:32:51 +00002023 // Add the class itself. If we've already seen this class, we don't
2024 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00002025 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00002026 return;
2027
Mike Stump1eb44332009-09-09 15:08:12 +00002028 // -- If T is a template-id, its associated namespaces and classes are
2029 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002030 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00002031 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00002032 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00002033 // namespaces in which any template template arguments are defined; and
2034 // the classes in which any member templates used as template template
2035 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00002036 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00002037 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00002038 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2039 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2040 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002041 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002042 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002043 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Douglas Gregor69be8d62009-07-08 07:51:57 +00002045 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2046 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00002047 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002048 }
Mike Stump1eb44332009-09-09 15:08:12 +00002049
John McCall86ff3082010-02-04 22:26:26 +00002050 // Only recurse into base classes for complete types.
2051 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00002052 QualType type = Result.S.Context.getTypeDeclType(Class);
2053 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
2054 /*no diagnostic*/ 0))
2055 return;
John McCall86ff3082010-02-04 22:26:26 +00002056 }
2057
Douglas Gregorfa047642009-02-04 00:32:51 +00002058 // Add direct and indirect base classes along with their associated
2059 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002060 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00002061 Bases.push_back(Class);
2062 while (!Bases.empty()) {
2063 // Pop this class off the stack.
Robert Wilhelm344472e2013-08-23 16:11:15 +00002064 Class = Bases.pop_back_val();
Douglas Gregorfa047642009-02-04 00:32:51 +00002065
2066 // Visit the base classes.
2067 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
2068 BaseEnd = Class->bases_end();
2069 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002070 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00002071 // In dependent contexts, we do ADL twice, and the first time around,
2072 // the base type might be a dependent TemplateSpecializationType, or a
2073 // TemplateTypeParmType. If that happens, simply ignore it.
2074 // FIXME: If we want to support export, we probably need to add the
2075 // namespace of the template in a TemplateSpecializationType, or even
2076 // the classes and namespaces of known non-dependent arguments.
2077 if (!BaseType)
2078 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002079 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002080 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002081 // Find the associated namespace for this base class.
2082 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00002083 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002084
2085 // Make sure we visit the bases of this base class.
2086 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2087 Bases.push_back(BaseDecl);
2088 }
2089 }
2090 }
2091}
2092
2093// \brief Add the associated classes and namespaces for
2094// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00002095// (C++ [basic.lookup.koenig]p2).
2096static void
John McCallc7e04da2010-05-28 18:45:08 +00002097addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002098 // C++ [basic.lookup.koenig]p2:
2099 //
2100 // For each argument type T in the function call, there is a set
2101 // of zero or more associated namespaces and a set of zero or more
2102 // associated classes to be considered. The sets of namespaces and
2103 // classes is determined entirely by the types of the function
2104 // arguments (and the namespace of any template template
2105 // argument). Typedef names and using-declarations used to specify
2106 // the types do not contribute to this set. The sets of namespaces
2107 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00002108
Chris Lattner5f9e2722011-07-23 10:55:15 +00002109 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00002110 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2111
Douglas Gregorfa047642009-02-04 00:32:51 +00002112 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00002113 switch (T->getTypeClass()) {
2114
2115#define TYPE(Class, Base)
2116#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2117#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2118#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2119#define ABSTRACT_TYPE(Class, Base)
2120#include "clang/AST/TypeNodes.def"
2121 // T is canonical. We can also ignore dependent types because
2122 // we don't need to do ADL at the definition point, but if we
2123 // wanted to implement template export (or if we find some other
2124 // use for associated classes and namespaces...) this would be
2125 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00002126 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002127
John McCallfa4edcf2010-05-28 06:08:54 +00002128 // -- If T is a pointer to U or an array of U, its associated
2129 // namespaces and classes are those associated with U.
2130 case Type::Pointer:
2131 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2132 continue;
2133 case Type::ConstantArray:
2134 case Type::IncompleteArray:
2135 case Type::VariableArray:
2136 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2137 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002138
John McCallfa4edcf2010-05-28 06:08:54 +00002139 // -- If T is a fundamental type, its associated sets of
2140 // namespaces and classes are both empty.
2141 case Type::Builtin:
2142 break;
2143
2144 // -- If T is a class type (including unions), its associated
2145 // classes are: the class itself; the class of which it is a
2146 // member, if any; and its direct and indirect base
2147 // classes. Its associated namespaces are the namespaces in
2148 // which its associated classes are defined.
2149 case Type::Record: {
2150 CXXRecordDecl *Class
2151 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002152 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00002153 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002154 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00002155
John McCallfa4edcf2010-05-28 06:08:54 +00002156 // -- If T is an enumeration type, its associated namespace is
2157 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002158 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00002159 // it has no associated class.
2160 case Type::Enum: {
2161 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002162
John McCallfa4edcf2010-05-28 06:08:54 +00002163 DeclContext *Ctx = Enum->getDeclContext();
2164 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002165 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002166
John McCallfa4edcf2010-05-28 06:08:54 +00002167 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002168 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002169
John McCallfa4edcf2010-05-28 06:08:54 +00002170 break;
2171 }
2172
2173 // -- If T is a function type, its associated namespaces and
2174 // classes are those associated with the function parameter
2175 // types and those associated with the return type.
2176 case Type::FunctionProto: {
2177 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2178 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2179 ArgEnd = Proto->arg_type_end();
2180 Arg != ArgEnd; ++Arg)
2181 Queue.push_back(Arg->getTypePtr());
2182 // fallthrough
2183 }
2184 case Type::FunctionNoProto: {
2185 const FunctionType *FnType = cast<FunctionType>(T);
2186 T = FnType->getResultType().getTypePtr();
2187 continue;
2188 }
2189
2190 // -- If T is a pointer to a member function of a class X, its
2191 // associated namespaces and classes are those associated
2192 // with the function parameter types and return type,
2193 // together with those associated with X.
2194 //
2195 // -- If T is a pointer to a data member of class X, its
2196 // associated namespaces and classes are those associated
2197 // with the member type together with those associated with
2198 // X.
2199 case Type::MemberPointer: {
2200 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2201
2202 // Queue up the class type into which this points.
2203 Queue.push_back(MemberPtr->getClass());
2204
2205 // And directly continue with the pointee type.
2206 T = MemberPtr->getPointeeType().getTypePtr();
2207 continue;
2208 }
2209
2210 // As an extension, treat this like a normal pointer.
2211 case Type::BlockPointer:
2212 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2213 continue;
2214
2215 // References aren't covered by the standard, but that's such an
2216 // obvious defect that we cover them anyway.
2217 case Type::LValueReference:
2218 case Type::RValueReference:
2219 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2220 continue;
2221
2222 // These are fundamental types.
2223 case Type::Vector:
2224 case Type::ExtVector:
2225 case Type::Complex:
2226 break;
2227
Richard Smithdc7a4f52013-04-30 13:56:41 +00002228 // Non-deduced auto types only get here for error cases.
2229 case Type::Auto:
2230 break;
2231
Douglas Gregorf25760e2011-04-12 01:02:45 +00002232 // If T is an Objective-C object or interface type, or a pointer to an
2233 // object or interface type, the associated namespace is the global
2234 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002235 case Type::ObjCObject:
2236 case Type::ObjCInterface:
2237 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002238 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002239 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002240
2241 // Atomic types are just wrappers; use the associations of the
2242 // contained type.
2243 case Type::Atomic:
2244 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2245 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002246 }
2247
Robert Wilhelm344472e2013-08-23 16:11:15 +00002248 if (Queue.empty())
2249 break;
2250 T = Queue.pop_back_val();
Douglas Gregorfa047642009-02-04 00:32:51 +00002251 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002252}
2253
2254/// \brief Find the associated classes and namespaces for
2255/// argument-dependent lookup for a call with the given set of
2256/// arguments.
2257///
2258/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002259/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002260/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm834c0582013-08-09 18:02:13 +00002261void Sema::FindAssociatedClassesAndNamespaces(
2262 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2263 AssociatedNamespaceSet &AssociatedNamespaces,
2264 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002265 AssociatedNamespaces.clear();
2266 AssociatedClasses.clear();
2267
John McCall42f48fb2012-08-24 20:38:34 +00002268 AssociatedLookup Result(*this, InstantiationLoc,
2269 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002270
Douglas Gregorfa047642009-02-04 00:32:51 +00002271 // C++ [basic.lookup.koenig]p2:
2272 // For each argument type T in the function call, there is a set
2273 // of zero or more associated namespaces and a set of zero or more
2274 // associated classes to be considered. The sets of namespaces and
2275 // classes is determined entirely by the types of the function
2276 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002277 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002278 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002279 Expr *Arg = Args[ArgIdx];
2280
2281 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002282 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002283 continue;
2284 }
2285
2286 // [...] In addition, if the argument is the name or address of a
2287 // set of overloaded functions and/or function templates, its
2288 // associated classes and namespaces are the union of those
2289 // associated with each of the members of the set: the namespace
2290 // in which the function or function template is defined and the
2291 // classes and namespaces associated with its (non-dependent)
2292 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002293 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002294 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002295 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002296 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002297
John McCallc7e04da2010-05-28 18:45:08 +00002298 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2299 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002300
John McCallc7e04da2010-05-28 18:45:08 +00002301 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2302 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002303 // Look through any using declarations to find the underlying function.
2304 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002305
Chandler Carruthbd647292009-12-29 06:17:27 +00002306 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2307 if (!FDecl)
2308 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002309
2310 // Add the classes and namespaces associated with the parameter
2311 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002312 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002313 }
2314 }
2315}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002316
2317/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2318/// an acceptable non-member overloaded operator for a call whose
2319/// arguments have types T1 (and, if non-empty, T2). This routine
2320/// implements the check in C++ [over.match.oper]p3b2 concerning
2321/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002322static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002323IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2324 QualType T1, QualType T2,
2325 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002326 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2327 return true;
2328
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002329 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2330 return true;
2331
John McCall183700f2009-09-21 23:43:11 +00002332 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002333 if (Proto->getNumArgs() < 1)
2334 return false;
2335
2336 if (T1->isEnumeralType()) {
2337 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002338 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002339 return true;
2340 }
2341
2342 if (Proto->getNumArgs() < 2)
2343 return false;
2344
2345 if (!T2.isNull() && T2->isEnumeralType()) {
2346 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002347 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002348 return true;
2349 }
2350
2351 return false;
2352}
2353
John McCall7d384dd2009-11-18 07:57:50 +00002354NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002355 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002356 LookupNameKind NameKind,
2357 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002358 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002359 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002360 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002361}
2362
Douglas Gregor6e378de2009-04-23 23:18:26 +00002363/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002364ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002365 SourceLocation IdLoc,
2366 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002367 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002368 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002369 return cast_or_null<ObjCProtocolDecl>(D);
2370}
2371
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002372void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002373 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002374 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002375 // C++ [over.match.oper]p3:
2376 // -- The set of non-member candidates is the result of the
2377 // unqualified lookup of operator@ in the context of the
2378 // expression according to the usual rules for name lookup in
2379 // unqualified function calls (3.4.2) except that all member
2380 // functions are ignored. However, if no operand has a class
2381 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002382 // that have a first parameter of type T1 or "reference to
2383 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002384 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002385 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002386 // when T2 is an enumeration type, are candidate functions.
2387 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002388 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2389 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002391 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2392
John McCallf36e02d2009-10-09 21:13:30 +00002393 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002394 return;
2395
2396 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2397 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002398 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2399 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002400 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002401 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002402 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002403 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002404 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002405 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002406 // later?
2407 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002408 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002409 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002410 }
2411}
2412
Sean Huntc39b6bc2011-06-24 02:11:39 +00002413Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002414 CXXSpecialMember SM,
2415 bool ConstArg,
2416 bool VolatileArg,
2417 bool RValueThis,
2418 bool ConstThis,
2419 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002420 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002421 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002422 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002423 if (RValueThis || ConstThis || VolatileThis)
2424 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2425 "constructors and destructors always have unqualified lvalue this");
2426 if (ConstArg || VolatileArg)
2427 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2428 "parameter-less special members can't have qualified arguments");
2429
2430 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002431 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002432 ID.AddInteger(SM);
2433 ID.AddInteger(ConstArg);
2434 ID.AddInteger(VolatileArg);
2435 ID.AddInteger(RValueThis);
2436 ID.AddInteger(ConstThis);
2437 ID.AddInteger(VolatileThis);
2438
2439 void *InsertPoint;
2440 SpecialMemberOverloadResult *Result =
2441 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2442
2443 // This was already cached
2444 if (Result)
2445 return Result;
2446
Sean Hunt30543582011-06-07 00:11:58 +00002447 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2448 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002449 SpecialMemberCache.InsertNode(Result, InsertPoint);
2450
2451 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002452 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002453 DeclareImplicitDestructor(RD);
2454 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002455 assert(DD && "record without a destructor");
2456 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002457 Result->setKind(DD->isDeleted() ?
2458 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002459 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002460 return Result;
2461 }
2462
Sean Huntb320e0c2011-06-10 03:50:41 +00002463 // Prepare for overload resolution. Here we construct a synthetic argument
2464 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002465 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002466 DeclarationName Name;
2467 Expr *Arg = 0;
2468 unsigned NumArgs;
2469
Richard Smith704c8f72012-04-20 18:46:14 +00002470 QualType ArgType = CanTy;
2471 ExprValueKind VK = VK_LValue;
2472
Sean Huntb320e0c2011-06-10 03:50:41 +00002473 if (SM == CXXDefaultConstructor) {
2474 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2475 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002476 if (RD->needsImplicitDefaultConstructor())
2477 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002478 } else {
2479 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2480 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002481 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002482 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002483 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002484 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002485 } else {
2486 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002487 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002488 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002489 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002490 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002491 }
2492
Sean Huntb320e0c2011-06-10 03:50:41 +00002493 if (ConstArg)
2494 ArgType.addConst();
2495 if (VolatileArg)
2496 ArgType.addVolatile();
2497
2498 // This isn't /really/ specified by the standard, but it's implied
2499 // we should be working from an RValue in the case of move to ensure
2500 // that we prefer to bind to rvalue references, and an LValue in the
2501 // case of copy to ensure we don't bind to rvalue references.
2502 // Possibly an XValue is actually correct in the case of move, but
2503 // there is no semantic difference for class types in this restricted
2504 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002505 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002506 VK = VK_LValue;
2507 else
2508 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002509 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002510
Richard Smith704c8f72012-04-20 18:46:14 +00002511 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2512
2513 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002514 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002515 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002516 }
2517
2518 // Create the object argument
2519 QualType ThisTy = CanTy;
2520 if (ConstThis)
2521 ThisTy.addConst();
2522 if (VolatileThis)
2523 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002524 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002525 OpaqueValueExpr(SourceLocation(), ThisTy,
2526 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002527
2528 // Now we perform lookup on the name we computed earlier and do overload
2529 // resolution. Lookup is only performed directly into the class since there
2530 // will always be a (possibly implicit) declaration to shadow any others.
2531 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002532 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00002533 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002534 "lookup for a constructor or assignment operator was empty");
Chandler Carruthab4e0c02013-08-18 07:20:52 +00002535
2536 // Copy the candidates as our processing of them may load new declarations
2537 // from an external source and invalidate lookup_result.
2538 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2539
2540 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithb60fae52013-09-09 16:55:27 +00002541 E = Candidates.end();
Chandler Carruthab4e0c02013-08-18 07:20:52 +00002542 I != E; ++I) {
2543 NamedDecl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002544
Sean Huntc39b6bc2011-06-24 02:11:39 +00002545 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002546 continue;
2547
Sean Huntc39b6bc2011-06-24 02:11:39 +00002548 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2549 // FIXME: [namespace.udecl]p15 says that we should only consider a
2550 // using declaration here if it does not match a declaration in the
2551 // derived class. We do not implement this correctly in other cases
2552 // either.
2553 Cand = U->getTargetDecl();
2554
2555 if (Cand->isInvalidDecl())
2556 continue;
2557 }
2558
2559 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002560 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002561 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002562 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2563 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002564 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002565 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2566 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002567 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002568 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002569 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2570 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002571 RD, 0, ThisTy, Classification,
2572 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002573 OCS, true);
2574 else
2575 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002576 0, llvm::makeArrayRef(&Arg, NumArgs),
2577 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002578 } else {
2579 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002580 }
2581 }
2582
2583 OverloadCandidateSet::iterator Best;
2584 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2585 case OR_Success:
2586 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002587 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002588 break;
2589
2590 case OR_Deleted:
2591 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002592 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002593 break;
2594
2595 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002596 Result->setMethod(0);
2597 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2598 break;
2599
Sean Huntb320e0c2011-06-10 03:50:41 +00002600 case OR_No_Viable_Function:
2601 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002602 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002603 break;
2604 }
2605
2606 return Result;
2607}
2608
2609/// \brief Look up the default constructor for the given class.
2610CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002611 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002612 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2613 false, false);
2614
2615 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002616}
2617
Sean Hunt661c67a2011-06-21 23:42:56 +00002618/// \brief Look up the copying constructor for the given class.
2619CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002620 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002621 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2622 "non-const, non-volatile qualifiers for copy ctor arg");
2623 SpecialMemberOverloadResult *Result =
2624 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2625 Quals & Qualifiers::Volatile, false, false, false);
2626
Sean Huntc530d172011-06-10 04:44:37 +00002627 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2628}
2629
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002630/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002631CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2632 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002633 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002634 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2635 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002636
2637 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2638}
2639
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002640/// \brief Look up the constructors for the given class.
2641DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002642 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002643 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002644 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002645 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002646 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002647 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002648 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002649 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002650 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002651
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002652 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2653 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2654 return Class->lookup(Name);
2655}
2656
Sean Hunt661c67a2011-06-21 23:42:56 +00002657/// \brief Look up the copying assignment operator for the given class.
2658CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2659 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002660 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002661 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2662 "non-const, non-volatile qualifiers for copy assignment arg");
2663 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2664 "non-const, non-volatile qualifiers for copy assignment this");
2665 SpecialMemberOverloadResult *Result =
2666 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2667 Quals & Qualifiers::Volatile, RValueThis,
2668 ThisQuals & Qualifiers::Const,
2669 ThisQuals & Qualifiers::Volatile);
2670
Sean Hunt661c67a2011-06-21 23:42:56 +00002671 return Result->getMethod();
2672}
2673
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002674/// \brief Look up the moving assignment operator for the given class.
2675CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002676 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002677 bool RValueThis,
2678 unsigned ThisQuals) {
2679 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2680 "non-const, non-volatile qualifiers for copy assignment this");
2681 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002682 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2683 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002684 ThisQuals & Qualifiers::Const,
2685 ThisQuals & Qualifiers::Volatile);
2686
2687 return Result->getMethod();
2688}
2689
Douglas Gregordb89f282010-07-01 22:47:18 +00002690/// \brief Look for the destructor of the given class.
2691///
Sean Huntc5c9b532011-06-03 21:10:40 +00002692/// During semantic analysis, this routine should be used in lieu of
2693/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002694///
2695/// \returns The destructor for this class.
2696CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002697 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2698 false, false, false,
2699 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002700}
2701
Richard Smith36f5cfe2012-03-09 08:00:36 +00002702/// LookupLiteralOperator - Determine which literal operator should be used for
2703/// a user-defined literal, per C++11 [lex.ext].
2704///
2705/// Normal overload resolution is not used to select which literal operator to
2706/// call for a user-defined literal. Look up the provided literal operator name,
2707/// and filter the results to the appropriate set for the given argument types.
2708Sema::LiteralOperatorLookupResult
2709Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2710 ArrayRef<QualType> ArgTys,
Richard Smithb328e292013-10-07 19:57:58 +00002711 bool AllowRaw, bool AllowTemplate,
2712 bool AllowStringTemplate) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002713 LookupName(R, S);
2714 assert(R.getResultKind() != LookupResult::Ambiguous &&
2715 "literal operator lookup can't be ambiguous");
2716
2717 // Filter the lookup results appropriately.
2718 LookupResult::Filter F = R.makeFilter();
2719
Richard Smith36f5cfe2012-03-09 08:00:36 +00002720 bool FoundRaw = false;
Richard Smithb328e292013-10-07 19:57:58 +00002721 bool FoundTemplate = false;
2722 bool FoundStringTemplate = false;
Richard Smith36f5cfe2012-03-09 08:00:36 +00002723 bool FoundExactMatch = false;
2724
2725 while (F.hasNext()) {
2726 Decl *D = F.next();
2727 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2728 D = USD->getTargetDecl();
2729
Douglas Gregor7e0c2272013-04-10 05:18:00 +00002730 // If the declaration we found is invalid, skip it.
2731 if (D->isInvalidDecl()) {
2732 F.erase();
2733 continue;
2734 }
2735
Richard Smithb328e292013-10-07 19:57:58 +00002736 bool IsRaw = false;
2737 bool IsTemplate = false;
2738 bool IsStringTemplate = false;
2739 bool IsExactMatch = false;
2740
Richard Smith36f5cfe2012-03-09 08:00:36 +00002741 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2742 if (FD->getNumParams() == 1 &&
2743 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2744 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002745 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002746 IsExactMatch = true;
2747 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2748 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2749 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2750 IsExactMatch = false;
2751 break;
2752 }
2753 }
2754 }
2755 }
Richard Smithb328e292013-10-07 19:57:58 +00002756 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2757 TemplateParameterList *Params = FD->getTemplateParameters();
2758 if (Params->size() == 1)
2759 IsTemplate = true;
2760 else
2761 IsStringTemplate = true;
2762 }
Richard Smith36f5cfe2012-03-09 08:00:36 +00002763
2764 if (IsExactMatch) {
2765 FoundExactMatch = true;
Richard Smithb328e292013-10-07 19:57:58 +00002766 AllowRaw = false;
2767 AllowTemplate = false;
2768 AllowStringTemplate = false;
2769 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002770 // Go through again and remove the raw and template decls we've
2771 // already found.
2772 F.restart();
Richard Smithb328e292013-10-07 19:57:58 +00002773 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smith36f5cfe2012-03-09 08:00:36 +00002774 }
Richard Smithb328e292013-10-07 19:57:58 +00002775 } else if (AllowRaw && IsRaw) {
2776 FoundRaw = true;
2777 } else if (AllowTemplate && IsTemplate) {
2778 FoundTemplate = true;
2779 } else if (AllowStringTemplate && IsStringTemplate) {
2780 FoundStringTemplate = true;
Richard Smith36f5cfe2012-03-09 08:00:36 +00002781 } else {
2782 F.erase();
2783 }
2784 }
2785
2786 F.done();
2787
2788 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2789 // parameter type, that is used in preference to a raw literal operator
2790 // or literal operator template.
2791 if (FoundExactMatch)
2792 return LOLR_Cooked;
2793
2794 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2795 // operator template, but not both.
2796 if (FoundRaw && FoundTemplate) {
2797 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2798 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2799 Decl *D = *I;
2800 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2801 D = USD->getTargetDecl();
2802 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2803 D = FunTmpl->getTemplatedDecl();
2804 NoteOverloadCandidate(cast<FunctionDecl>(D));
2805 }
2806 return LOLR_Error;
2807 }
2808
2809 if (FoundRaw)
2810 return LOLR_Raw;
2811
2812 if (FoundTemplate)
2813 return LOLR_Template;
2814
Richard Smithb328e292013-10-07 19:57:58 +00002815 if (FoundStringTemplate)
2816 return LOLR_StringTemplate;
2817
Richard Smith36f5cfe2012-03-09 08:00:36 +00002818 // Didn't find anything we could use.
2819 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2820 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb328e292013-10-07 19:57:58 +00002821 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2822 << (AllowTemplate || AllowStringTemplate);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002823 return LOLR_Error;
2824}
2825
John McCall7edb5fd2010-01-26 07:16:45 +00002826void ADLResult::insert(NamedDecl *New) {
2827 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2828
2829 // If we haven't yet seen a decl for this key, or the last decl
2830 // was exactly this one, we're done.
2831 if (Old == 0 || Old == New) {
2832 Old = New;
2833 return;
2834 }
2835
2836 // Otherwise, decide which is a more recent redeclaration.
2837 FunctionDecl *OldFD, *NewFD;
2838 if (isa<FunctionTemplateDecl>(New)) {
2839 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2840 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2841 } else {
2842 OldFD = cast<FunctionDecl>(Old);
2843 NewFD = cast<FunctionDecl>(New);
2844 }
2845
2846 FunctionDecl *Cursor = NewFD;
2847 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002848 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002849
2850 // If we got to the end without finding OldFD, OldFD is the newer
2851 // declaration; leave things as they are.
2852 if (!Cursor) return;
2853
2854 // If we do find OldFD, then NewFD is newer.
2855 if (Cursor == OldFD) break;
2856
2857 // Otherwise, keep looking.
2858 }
2859
2860 Old = New;
2861}
2862
Sebastian Redl644be852009-10-23 19:23:15 +00002863void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm834c0582013-08-09 18:02:13 +00002864 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002865 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002866 // Find all of the associated namespaces and classes based on the
2867 // arguments we have.
2868 AssociatedNamespaceSet AssociatedNamespaces;
2869 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002870 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002871 AssociatedNamespaces,
2872 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002873
Sebastian Redl644be852009-10-23 19:23:15 +00002874 QualType T1, T2;
2875 if (Operator) {
2876 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002877 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002878 T2 = Args[1]->getType();
2879 }
2880
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002881 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002882 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2883 // and let Y be the lookup set produced by argument dependent
2884 // lookup (defined as follows). If X contains [...] then Y is
2885 // empty. Otherwise Y is the set of declarations found in the
2886 // namespaces associated with the argument types as described
2887 // below. The set of declarations found by the lookup of the name
2888 // is the union of X and Y.
2889 //
2890 // Here, we compute Y and add its members to the overloaded
2891 // candidate set.
2892 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002893 NSEnd = AssociatedNamespaces.end();
2894 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002895 // When considering an associated namespace, the lookup is the
2896 // same as the lookup performed when the associated namespace is
2897 // used as a qualifier (3.4.3.2) except that:
2898 //
2899 // -- Any using-directives in the associated namespace are
2900 // ignored.
2901 //
John McCall6ff07852009-08-07 22:18:02 +00002902 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002903 // associated classes are visible within their respective
2904 // namespaces even if they are not visible during an ordinary
2905 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002906 DeclContext::lookup_result R = (*NS)->lookup(Name);
2907 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2908 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002909 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002910 // If the only declaration here is an ordinary friend, consider
2911 // it only if it was declared in an associated classes.
Richard Smitha41c97a2013-09-20 01:15:31 +00002912 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2913 // If it's neither ordinarily visible nor a friend, we can't find it.
2914 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2915 continue;
2916
Richard Smith22050f22013-07-17 23:53:16 +00002917 bool DeclaredInAssociatedClass = false;
2918 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2919 DeclContext *LexDC = DI->getLexicalDeclContext();
2920 if (isa<CXXRecordDecl>(LexDC) &&
2921 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2922 DeclaredInAssociatedClass = true;
2923 break;
2924 }
2925 }
2926 if (!DeclaredInAssociatedClass)
John McCall3f9a8a62009-08-11 06:59:38 +00002927 continue;
2928 }
Mike Stump1eb44332009-09-09 15:08:12 +00002929
John McCalla113e722010-01-26 06:04:06 +00002930 if (isa<UsingShadowDecl>(D))
2931 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002932
John McCalla113e722010-01-26 06:04:06 +00002933 if (isa<FunctionDecl>(D)) {
2934 if (Operator &&
2935 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2936 T1, T2, Context))
2937 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002938 } else if (!isa<FunctionTemplateDecl>(D))
2939 continue;
2940
2941 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002942 }
2943 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002944}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002945
2946//----------------------------------------------------------------------------
2947// Search for all visible declarations.
2948//----------------------------------------------------------------------------
2949VisibleDeclConsumer::~VisibleDeclConsumer() { }
2950
Richard Smithd67679d2013-08-20 20:35:18 +00002951bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2952
Douglas Gregor546be3c2009-12-30 17:04:44 +00002953namespace {
2954
2955class ShadowContextRAII;
2956
2957class VisibleDeclsRecord {
2958public:
2959 /// \brief An entry in the shadow map, which is optimized to store a
2960 /// single declaration (the common case) but can also store a list
2961 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002962 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002963
2964private:
2965 /// \brief A mapping from declaration names to the declarations that have
2966 /// this name within a particular scope.
2967 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2968
2969 /// \brief A list of shadow maps, which is used to model name hiding.
2970 std::list<ShadowMap> ShadowMaps;
2971
2972 /// \brief The declaration contexts we have already visited.
2973 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2974
2975 friend class ShadowContextRAII;
2976
2977public:
2978 /// \brief Determine whether we have already visited this context
2979 /// (and, if not, note that we are going to visit that context now).
2980 bool visitedContext(DeclContext *Ctx) {
2981 return !VisitedContexts.insert(Ctx);
2982 }
2983
Douglas Gregor8071e422010-08-15 06:18:01 +00002984 bool alreadyVisitedContext(DeclContext *Ctx) {
2985 return VisitedContexts.count(Ctx);
2986 }
2987
Douglas Gregor546be3c2009-12-30 17:04:44 +00002988 /// \brief Determine whether the given declaration is hidden in the
2989 /// current scope.
2990 ///
2991 /// \returns the declaration that hides the given declaration, or
2992 /// NULL if no such declaration exists.
2993 NamedDecl *checkHidden(NamedDecl *ND);
2994
2995 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002996 void add(NamedDecl *ND) {
2997 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2998 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002999};
3000
3001/// \brief RAII object that records when we've entered a shadow context.
3002class ShadowContextRAII {
3003 VisibleDeclsRecord &Visible;
3004
3005 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3006
3007public:
3008 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3009 Visible.ShadowMaps.push_back(ShadowMap());
3010 }
3011
3012 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003013 Visible.ShadowMaps.pop_back();
3014 }
3015};
3016
3017} // end anonymous namespace
3018
Douglas Gregor546be3c2009-12-30 17:04:44 +00003019NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00003020 // Look through using declarations.
3021 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003022
Douglas Gregor546be3c2009-12-30 17:04:44 +00003023 unsigned IDNS = ND->getIdentifierNamespace();
3024 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3025 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3026 SM != SMEnd; ++SM) {
3027 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3028 if (Pos == SM->end())
3029 continue;
3030
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003031 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00003032 IEnd = Pos->second.end();
3033 I != IEnd; ++I) {
3034 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00003035 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003036 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00003037 Decl::IDNS_ObjCProtocol)))
3038 continue;
3039
3040 // Protocols are in distinct namespaces from everything else.
3041 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3042 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3043 (*I)->getIdentifierNamespace() != IDNS)
3044 continue;
3045
Douglas Gregor0cc84042010-01-14 15:47:35 +00003046 // Functions and function templates in the same scope overload
3047 // rather than hide. FIXME: Look for hiding based on function
3048 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00003049 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00003050 ND->isFunctionOrFunctionTemplate() &&
3051 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00003052 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003053
Douglas Gregor546be3c2009-12-30 17:04:44 +00003054 // We've found a declaration that hides this one.
3055 return *I;
3056 }
3057 }
3058
3059 return 0;
3060}
3061
3062static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3063 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003064 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00003065 VisibleDeclConsumer &Consumer,
3066 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00003067 if (!Ctx)
3068 return;
3069
Douglas Gregor546be3c2009-12-30 17:04:44 +00003070 // Make sure we don't visit the same context twice.
3071 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3072 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003073
Douglas Gregor4923aa22010-07-02 20:37:36 +00003074 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3075 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3076
Douglas Gregor546be3c2009-12-30 17:04:44 +00003077 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00003078 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
3079 LEnd = Ctx->lookups_end();
3080 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003081 DeclContext::lookup_result R = *L;
3082 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3083 ++I) {
3084 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00003085 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003086 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003087 Visited.add(ND);
3088 }
Douglas Gregor70c23352010-12-09 21:44:02 +00003089 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003090 }
3091 }
3092
3093 // Traverse using directives for qualified name lookup.
3094 if (QualifiedNameLookup) {
3095 ShadowContextRAII Shadow(Visited);
3096 DeclContext::udir_iterator I, E;
3097 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003098 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003099 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003100 }
3101 }
3102
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003103 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003104 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00003105 if (!Record->hasDefinition())
3106 return;
3107
Douglas Gregor546be3c2009-12-30 17:04:44 +00003108 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
3109 BEnd = Record->bases_end();
3110 B != BEnd; ++B) {
3111 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112
Douglas Gregor546be3c2009-12-30 17:04:44 +00003113 // Don't look into dependent bases, because name lookup can't look
3114 // there anyway.
3115 if (BaseType->isDependentType())
3116 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003117
Douglas Gregor546be3c2009-12-30 17:04:44 +00003118 const RecordType *Record = BaseType->getAs<RecordType>();
3119 if (!Record)
3120 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121
Douglas Gregor546be3c2009-12-30 17:04:44 +00003122 // FIXME: It would be nice to be able to determine whether referencing
3123 // a particular member would be ambiguous. For example, given
3124 //
3125 // struct A { int member; };
3126 // struct B { int member; };
3127 // struct C : A, B { };
3128 //
3129 // void f(C *c) { c->### }
3130 //
3131 // accessing 'member' would result in an ambiguity. However, we
3132 // could be smart enough to qualify the member with the base
3133 // class, e.g.,
3134 //
3135 // c->B::member
3136 //
3137 // or
3138 //
3139 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003140
Douglas Gregor546be3c2009-12-30 17:04:44 +00003141 // Find results in this base class (and its bases).
3142 ShadowContextRAII Shadow(Visited);
3143 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003144 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003145 }
3146 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003147
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003148 // Traverse the contexts of Objective-C classes.
3149 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3150 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00003151 for (ObjCInterfaceDecl::visible_categories_iterator
3152 Cat = IFace->visible_categories_begin(),
3153 CatEnd = IFace->visible_categories_end();
3154 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003155 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00003156 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003157 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003158 }
3159
3160 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003161 for (ObjCInterfaceDecl::all_protocol_iterator
3162 I = IFace->all_referenced_protocol_begin(),
3163 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003164 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003165 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003166 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003167 }
3168
3169 // Traverse the superclass.
3170 if (IFace->getSuperClass()) {
3171 ShadowContextRAII Shadow(Visited);
3172 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003173 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003175
Douglas Gregorc220a182010-04-19 18:02:19 +00003176 // If there is an implementation, traverse it. We do this to find
3177 // synthesized ivars.
3178 if (IFace->getImplementation()) {
3179 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003180 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00003181 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00003182 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003183 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3184 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3185 E = Protocol->protocol_end(); I != E; ++I) {
3186 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003187 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003188 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003189 }
3190 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3191 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3192 E = Category->protocol_end(); I != E; ++I) {
3193 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003194 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003195 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003196 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003197
Douglas Gregorc220a182010-04-19 18:02:19 +00003198 // If there is an implementation, traverse it.
3199 if (Category->getImplementation()) {
3200 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003201 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00003202 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003203 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003204 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003205}
3206
3207static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3208 UnqualUsingDirectiveSet &UDirs,
3209 VisibleDeclConsumer &Consumer,
3210 VisibleDeclsRecord &Visited) {
3211 if (!S)
3212 return;
3213
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214 if (!S->getEntity() ||
3215 (!S->getParent() &&
Ted Kremenekf0d58612013-10-08 17:08:03 +00003216 !Visited.alreadyVisitedContext(S->getEntity())) ||
3217 (S->getEntity())->isFunctionOrMethod()) {
Richard Smitha41c97a2013-09-20 01:15:31 +00003218 FindLocalExternScope FindLocals(Result);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003219 // Walk through the declarations in this Scope.
3220 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3221 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003222 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003223 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003224 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003225 Visited.add(ND);
3226 }
3227 }
3228 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003229
Douglas Gregor711be1e2010-03-15 14:33:29 +00003230 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003231 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003232 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003233 // Look into this scope's declaration context, along with any of its
3234 // parent lookup contexts (e.g., enclosing classes), up to the point
3235 // where we hit the context stored in the next outer scope.
Ted Kremenekf0d58612013-10-08 17:08:03 +00003236 Entity = S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003237 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003238
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003239 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003240 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003241 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3242 if (Method->isInstanceMethod()) {
3243 // For instance methods, look for ivars in the method's interface.
3244 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3245 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003246 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003247 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithd67679d2013-08-20 20:35:18 +00003248 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003249 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003250 }
3251
3252 // We've already performed all of the name lookup that we need
3253 // to for Objective-C methods; the next context will be the
3254 // outer scope.
3255 break;
3256 }
3257
Douglas Gregor546be3c2009-12-30 17:04:44 +00003258 if (Ctx->isFunctionOrMethod())
3259 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003260
3261 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003262 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003263 }
3264 } else if (!S->getParent()) {
3265 // Look into the translation unit scope. We walk through the translation
3266 // unit's declaration context, because the Scope itself won't have all of
3267 // the declarations if we loaded a precompiled header.
3268 // FIXME: We would like the translation unit's Scope object to point to the
3269 // translation unit, so we don't need this special "if" branch. However,
3270 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003271 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003272 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003273 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003274 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003275 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003276 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003277 }
3278
Douglas Gregor546be3c2009-12-30 17:04:44 +00003279 if (Entity) {
3280 // Lookup visible declarations in any namespaces found by using
3281 // directives.
3282 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3283 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3284 for (; UI != UEnd; ++UI)
3285 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003286 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003287 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003288 }
3289
3290 // Lookup names in the parent scope.
3291 ShadowContextRAII Shadow(Visited);
3292 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3293}
3294
3295void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003296 VisibleDeclConsumer &Consumer,
3297 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003298 // Determine the set of using directives available during
3299 // unqualified name lookup.
3300 Scope *Initial = S;
3301 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003302 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003303 // Find the first namespace or translation-unit scope.
3304 while (S && !isNamespaceOrTranslationUnitScope(S))
3305 S = S->getParent();
3306
3307 UDirs.visitScopeChain(Initial, S);
3308 }
3309 UDirs.done();
3310
3311 // Look for visible declarations.
3312 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003313 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003314 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003315 if (!IncludeGlobalScope)
3316 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003317 ShadowContextRAII Shadow(Visited);
3318 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3319}
3320
3321void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003322 VisibleDeclConsumer &Consumer,
3323 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003324 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003325 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003326 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003327 if (!IncludeGlobalScope)
3328 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003329 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003330 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003331 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003332}
3333
Chris Lattner4ae493c2011-02-18 02:08:43 +00003334/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003335/// If GnuLabelLoc is a valid source location, then this is a definition
3336/// of an __label__ label name, otherwise it is a normal label definition
3337/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003338LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003339 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003340 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003341 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003342
3343 if (GnuLabelLoc.isValid()) {
3344 // Local label definitions always shadow existing labels.
3345 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3346 Scope *S = CurScope;
3347 PushOnScopeChains(Res, S, true);
3348 return cast<LabelDecl>(Res);
3349 }
3350
3351 // Not a GNU local label.
3352 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3353 // If we found a label, check to see if it is in the same context as us.
3354 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003355 if (Res && Res->getDeclContext() != CurContext)
3356 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003357 if (Res == 0) {
3358 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003359 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3360 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003361 assert(S && "Not in a function?");
3362 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003363 }
Chris Lattner337e5502011-02-18 01:27:55 +00003364 return cast<LabelDecl>(Res);
3365}
3366
3367//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003368// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003369//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003370
3371namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003372
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003373typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003374typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003375typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003376
3377static const unsigned MaxTypoDistanceResultSets = 5;
3378
Douglas Gregor546be3c2009-12-30 17:04:44 +00003379class TypoCorrectionConsumer : public VisibleDeclConsumer {
3380 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003381 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003382
3383 /// \brief The results found that have the smallest edit distance
3384 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003385 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003386 /// The pointer value being set to the current DeclContext indicates
3387 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003388 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003389
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003390 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003391
Douglas Gregor546be3c2009-12-30 17:04:44 +00003392public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003393 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003394 : Typo(Typo->getName()),
Richard Smithd67679d2013-08-20 20:35:18 +00003395 SemaRef(SemaRef) {}
3396
3397 bool includeHiddenDecls() const { return true; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003398
Erik Verbruggend1205962011-10-06 07:27:49 +00003399 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3400 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003401 void FoundName(StringRef Name);
3402 void addKeywordResult(StringRef Keyword);
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003403 void addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS = NULL,
3404 bool isKeyword = false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003405 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003406
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003407 typedef TypoResultsMap::iterator result_iterator;
3408 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003409 distance_iterator begin() { return CorrectionResults.begin(); }
3410 distance_iterator end() { return CorrectionResults.end(); }
3411 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3412 unsigned size() const { return CorrectionResults.size(); }
3413 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003414
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003415 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003416 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003417 }
3418
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003419 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003420 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003421 return (std::numeric_limits<unsigned>::max)();
3422
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003423 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003424 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003425 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003426
3427 TypoResultsMap &getBestResults() {
3428 return CorrectionResults.begin()->second;
3429 }
3430
Douglas Gregor546be3c2009-12-30 17:04:44 +00003431};
3432
3433}
3434
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003435void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003436 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003437 // Don't consider hidden names for typo correction.
3438 if (Hiding)
3439 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003440
Douglas Gregor546be3c2009-12-30 17:04:44 +00003441 // Only consider entities with identifiers for names, ignoring
3442 // special names (constructors, overloaded operators, selectors,
3443 // etc.).
3444 IdentifierInfo *Name = ND->getIdentifier();
3445 if (!Name)
3446 return;
3447
Richard Smithd67679d2013-08-20 20:35:18 +00003448 // Only consider visible declarations and declarations from modules with
3449 // names that exactly match.
3450 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3451 !findAcceptableDecl(SemaRef, ND))
3452 return;
3453
Douglas Gregor95f42922010-10-14 22:11:03 +00003454 FoundName(Name->getName());
3455}
3456
Chris Lattner5f9e2722011-07-23 10:55:15 +00003457void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003458 // Compute the edit distance between the typo and the name of this
3459 // entity, and add the identifier to the list of results.
3460 addName(Name, NULL);
3461}
3462
3463void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3464 // Compute the edit distance between the typo and this keyword,
3465 // and add the keyword to the list of results.
3466 addName(Keyword, NULL, NULL, true);
3467}
3468
3469void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3470 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003471 // Use a simple length-based heuristic to determine the minimum possible
3472 // edit distance. If the minimum isn't good enough, bail out early.
3473 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003474 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003475 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003476
Douglas Gregora1194772010-10-19 22:14:33 +00003477 // Compute an upper bound on the allowable edit distance, so that the
3478 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003479 unsigned UpperBound = (Typo.size() + 2) / 3 + 1;
3480 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3481 if (ED >= UpperBound) return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003482
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003483 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003484 if (isKeyword) TC.makeKeyword();
3485 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003486}
3487
3488void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003489 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003490 TypoResultList &CList =
3491 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003492
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003493 if (!CList.empty() && !CList.back().isResolved())
3494 CList.pop_back();
3495 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3496 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3497 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3498 RI != RIEnd; ++RI) {
3499 // If the Correction refers to a decl already in the result list,
3500 // replace the existing result if the string representation of Correction
3501 // comes before the current result alphabetically, then stop as there is
3502 // nothing more to be done to add Correction to the candidate set.
3503 if (RI->getCorrectionDecl() == NewND) {
3504 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3505 *RI = Correction;
3506 return;
3507 }
3508 }
3509 }
3510 if (CList.empty() || Correction.isResolved())
3511 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003512
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003513 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3514 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003515}
3516
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003517// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3518// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3519// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3520static void getNestedNameSpecifierIdentifiers(
3521 NestedNameSpecifier *NNS,
3522 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3523 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3524 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3525 else
3526 Identifiers.clear();
3527
3528 const IdentifierInfo *II = NULL;
3529
3530 switch (NNS->getKind()) {
3531 case NestedNameSpecifier::Identifier:
3532 II = NNS->getAsIdentifier();
3533 break;
3534
3535 case NestedNameSpecifier::Namespace:
3536 if (NNS->getAsNamespace()->isAnonymousNamespace())
3537 return;
3538 II = NNS->getAsNamespace()->getIdentifier();
3539 break;
3540
3541 case NestedNameSpecifier::NamespaceAlias:
3542 II = NNS->getAsNamespaceAlias()->getIdentifier();
3543 break;
3544
3545 case NestedNameSpecifier::TypeSpecWithTemplate:
3546 case NestedNameSpecifier::TypeSpec:
3547 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3548 break;
3549
3550 case NestedNameSpecifier::Global:
3551 return;
3552 }
3553
3554 if (II)
3555 Identifiers.push_back(II);
3556}
3557
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003558namespace {
3559
3560class SpecifierInfo {
3561 public:
3562 DeclContext* DeclCtx;
3563 NestedNameSpecifier* NameSpecifier;
3564 unsigned EditDistance;
3565
3566 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3567 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3568};
3569
Chris Lattner5f9e2722011-07-23 10:55:15 +00003570typedef SmallVector<DeclContext*, 4> DeclContextList;
3571typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003572
3573class NamespaceSpecifierSet {
3574 ASTContext &Context;
3575 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003576 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3577 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003578 bool isSorted;
3579
3580 SpecifierInfoList Specifiers;
3581 llvm::SmallSetVector<unsigned, 4> Distances;
3582 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3583
3584 /// \brief Helper for building the list of DeclContexts between the current
3585 /// context and the top of the translation unit
3586 static DeclContextList BuildContextChain(DeclContext *Start);
3587
3588 void SortNamespaces();
3589
3590 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003591 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3592 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003593 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003594 isSorted(false) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003595 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3596 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3597 CurNameSpecifierIdentifiers);
3598 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003599 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003600 // context.
3601 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3602 CEnd = CurContextChain.rend();
3603 C != CEnd; ++C) {
3604 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3605 CurContextIdentifiers.push_back(ND->getIdentifier());
3606 }
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003607
3608 // Add the global context as a NestedNameSpecifier
3609 Distances.insert(1);
3610 DistanceMap[1].push_back(
3611 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3612 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003613 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003614
3615 /// \brief Add the namespace to the set, computing the corresponding
3616 /// NestedNameSpecifier and its distance in the process.
3617 void AddNamespace(NamespaceDecl *ND);
3618
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003619 /// \brief Add the record to the set, computing the corresponding
3620 /// NestedNameSpecifier and its distance in the process.
3621 void AddRecord(RecordDecl *RD);
3622
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003623 typedef SpecifierInfoList::iterator iterator;
3624 iterator begin() {
3625 if (!isSorted) SortNamespaces();
3626 return Specifiers.begin();
3627 }
3628 iterator end() { return Specifiers.end(); }
3629};
3630
3631}
3632
3633DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0db9d202013-04-08 21:55:21 +00003634 assert(Start && "Building a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003635 DeclContextList Chain;
3636 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3637 DC = DC->getLookupParent()) {
3638 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3639 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3640 !(ND && ND->isAnonymousNamespace()))
3641 Chain.push_back(DC->getPrimaryContext());
3642 }
3643 return Chain;
3644}
3645
3646void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003647 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003648 sortedDistances.append(Distances.begin(), Distances.end());
3649
3650 if (sortedDistances.size() > 1)
3651 std::sort(sortedDistances.begin(), sortedDistances.end());
3652
3653 Specifiers.clear();
Craig Topper09d19ef2013-07-04 03:08:24 +00003654 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3655 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003656 DI != DIEnd; ++DI) {
3657 SpecifierInfoList &SpecList = DistanceMap[*DI];
3658 Specifiers.append(SpecList.begin(), SpecList.end());
3659 }
3660
3661 isSorted = true;
3662}
3663
3664void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003665 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003666 NestedNameSpecifier *NNS = NULL;
3667 unsigned NumSpecifiers = 0;
3668 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003669 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003670
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003671 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003672 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3673 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003674 C != CEnd && !NamespaceDeclChain.empty() &&
3675 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003676 NamespaceDeclChain.pop_back();
3677 }
3678
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003679 // Add an explicit leading '::' specifier if needed.
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00003680 if (NamespaceDeclChain.empty()) {
3681 NamespaceDeclChain = FullNamespaceDeclChain;
3682 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3683 } else if (NamespaceDecl *ND =
3684 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003685 IdentifierInfo *Name = ND->getIdentifier();
3686 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3687 Name) != CurContextIdentifiers.end() ||
3688 std::find(CurNameSpecifierIdentifiers.begin(),
3689 CurNameSpecifierIdentifiers.end(),
3690 Name) != CurNameSpecifierIdentifiers.end()) {
3691 NamespaceDeclChain = FullNamespaceDeclChain;
3692 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3693 }
3694 }
3695
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003696 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3697 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3698 CEnd = NamespaceDeclChain.rend();
3699 C != CEnd; ++C) {
3700 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3701 if (ND) {
3702 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3703 ++NumSpecifiers;
3704 }
3705 }
3706
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003707 // If the built NestedNameSpecifier would be replacing an existing
3708 // NestedNameSpecifier, use the number of component identifiers that
3709 // would need to be changed as the edit distance instead of the number
3710 // of components in the built NestedNameSpecifier.
3711 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3712 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3713 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3714 NumSpecifiers = llvm::ComputeEditDistance(
Robert Wilhelm834c0582013-08-09 18:02:13 +00003715 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3716 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003717 }
3718
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003719 isSorted = false;
3720 Distances.insert(NumSpecifiers);
3721 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003722}
3723
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003724void NamespaceSpecifierSet::AddRecord(RecordDecl *RD) {
3725 if (!RD->isBeingDefined() && !RD->isCompleteDefinition())
3726 return;
3727
3728 DeclContext *Ctx = cast<DeclContext>(RD);
3729 NestedNameSpecifier *NNS = NULL;
3730 unsigned NumSpecifiers = 0;
3731 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3732 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3733
3734 // Eliminate common elements from the two DeclContext chains.
3735 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3736 CEnd = CurContextChain.rend();
3737 C != CEnd && !NamespaceDeclChain.empty() &&
3738 NamespaceDeclChain.back() == *C; ++C) {
3739 NamespaceDeclChain.pop_back();
3740 }
3741
3742 // Add an explicit leading '::' specifier if needed.
3743 if (NamespaceDeclChain.empty()) {
3744 NamespaceDeclChain = FullNamespaceDeclChain;
3745 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003746 } else if (NamedDecl *ND =
3747 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003748 IdentifierInfo *Name = ND->getIdentifier();
3749 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3750 Name) != CurContextIdentifiers.end() ||
3751 std::find(CurNameSpecifierIdentifiers.begin(),
3752 CurNameSpecifierIdentifiers.end(),
3753 Name) != CurNameSpecifierIdentifiers.end()) {
3754 NamespaceDeclChain = FullNamespaceDeclChain;
3755 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3756 }
3757 }
3758
3759 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3760 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3761 CEnd = NamespaceDeclChain.rend();
3762 C != CEnd; ++C) {
3763 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3764 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3765 ++NumSpecifiers;
3766 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3767 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3768 RD->getTypeForDecl());
3769 ++NumSpecifiers;
3770 }
3771 }
3772
3773 // If the built NestedNameSpecifier would be replacing an existing
3774 // NestedNameSpecifier, use the number of component identifiers that
3775 // would need to be changed as the edit distance instead of the number
3776 // of components in the built NestedNameSpecifier.
3777 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3778 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3779 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3780 NumSpecifiers = llvm::ComputeEditDistance(
3781 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3782 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3783 }
3784
3785 isSorted = false;
3786 Distances.insert(NumSpecifiers);
3787 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3788}
3789
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003790/// \brief Perform name lookup for a possible result for typo correction.
3791static void LookupPotentialTypoResult(Sema &SemaRef,
3792 LookupResult &Res,
3793 IdentifierInfo *Name,
3794 Scope *S, CXXScopeSpec *SS,
3795 DeclContext *MemberContext,
3796 bool EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00003797 bool isObjCIvarLookup,
3798 bool FindHidden) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003799 Res.suppressDiagnostics();
3800 Res.clear();
3801 Res.setLookupName(Name);
Richard Smithd67679d2013-08-20 20:35:18 +00003802 Res.setAllowHidden(FindHidden);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003803 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003804 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003805 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003806 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3807 Res.addDecl(Ivar);
3808 Res.resolveKind();
3809 return;
3810 }
3811 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003812
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003813 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3814 Res.addDecl(Prop);
3815 Res.resolveKind();
3816 return;
3817 }
3818 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003819
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003820 SemaRef.LookupQualifiedName(Res, MemberContext);
3821 return;
3822 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823
3824 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003825 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003827 // Fake ivar lookup; this should really be part of
3828 // LookupParsedName.
3829 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3830 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003831 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003832 (Res.isSingleResult() &&
3833 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003834 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003835 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3836 Res.addDecl(IV);
3837 Res.resolveKind();
3838 }
3839 }
3840 }
3841}
3842
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003843/// \brief Add keywords to the consumer as possible typo corrections.
3844static void AddKeywordsToConsumer(Sema &SemaRef,
3845 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003846 Scope *S, CorrectionCandidateCallback &CCC,
3847 bool AfterNestedNameSpecifier) {
3848 if (AfterNestedNameSpecifier) {
3849 // For 'X::', we know exactly which keywords can appear next.
3850 Consumer.addKeywordResult("template");
3851 if (CCC.WantExpressionKeywords)
3852 Consumer.addKeywordResult("operator");
3853 return;
3854 }
3855
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003856 if (CCC.WantObjCSuper)
3857 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003858
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003859 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003860 // Add type-specifier keywords to the set of results.
Craig Topper3aa29df2013-07-15 08:24:27 +00003861 static const char *const CTypeSpecs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003862 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003863 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003864 "_Complex", "_Imaginary",
3865 // storage-specifiers as well
3866 "extern", "inline", "static", "typedef"
3867 };
3868
Craig Topperb9602322013-07-15 03:38:40 +00003869 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003870 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3871 Consumer.addKeywordResult(CTypeSpecs[I]);
3872
David Blaikie4e4d0842012-03-11 07:00:24 +00003873 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003874 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003875 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003876 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003877 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003878 Consumer.addKeywordResult("_Bool");
3879
David Blaikie4e4d0842012-03-11 07:00:24 +00003880 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003881 Consumer.addKeywordResult("class");
3882 Consumer.addKeywordResult("typename");
3883 Consumer.addKeywordResult("wchar_t");
3884
Richard Smith80ad52f2013-01-02 11:42:31 +00003885 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003886 Consumer.addKeywordResult("char16_t");
3887 Consumer.addKeywordResult("char32_t");
3888 Consumer.addKeywordResult("constexpr");
3889 Consumer.addKeywordResult("decltype");
3890 Consumer.addKeywordResult("thread_local");
3891 }
3892 }
3893
David Blaikie4e4d0842012-03-11 07:00:24 +00003894 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003895 Consumer.addKeywordResult("typeof");
3896 }
3897
David Blaikie4e4d0842012-03-11 07:00:24 +00003898 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003899 Consumer.addKeywordResult("const_cast");
3900 Consumer.addKeywordResult("dynamic_cast");
3901 Consumer.addKeywordResult("reinterpret_cast");
3902 Consumer.addKeywordResult("static_cast");
3903 }
3904
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003905 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003906 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003907 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003908 Consumer.addKeywordResult("false");
3909 Consumer.addKeywordResult("true");
3910 }
3911
David Blaikie4e4d0842012-03-11 07:00:24 +00003912 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topper3aa29df2013-07-15 08:24:27 +00003913 static const char *const CXXExprs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003914 "delete", "new", "operator", "throw", "typeid"
3915 };
Craig Topperb9602322013-07-15 03:38:40 +00003916 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003917 for (unsigned I = 0; I != NumCXXExprs; ++I)
3918 Consumer.addKeywordResult(CXXExprs[I]);
3919
3920 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3921 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3922 Consumer.addKeywordResult("this");
3923
Richard Smith80ad52f2013-01-02 11:42:31 +00003924 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003925 Consumer.addKeywordResult("alignof");
3926 Consumer.addKeywordResult("nullptr");
3927 }
3928 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003929
3930 if (SemaRef.getLangOpts().C11) {
3931 // FIXME: We should not suggest _Alignof if the alignof macro
3932 // is present.
3933 Consumer.addKeywordResult("_Alignof");
3934 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003935 }
3936
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003937 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003938 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3939 // Statements.
Craig Topper3aa29df2013-07-15 08:24:27 +00003940 static const char *const CStmts[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003941 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Topperb9602322013-07-15 03:38:40 +00003942 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003943 for (unsigned I = 0; I != NumCStmts; ++I)
3944 Consumer.addKeywordResult(CStmts[I]);
3945
David Blaikie4e4d0842012-03-11 07:00:24 +00003946 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003947 Consumer.addKeywordResult("catch");
3948 Consumer.addKeywordResult("try");
3949 }
3950
3951 if (S && S->getBreakParent())
3952 Consumer.addKeywordResult("break");
3953
3954 if (S && S->getContinueParent())
3955 Consumer.addKeywordResult("continue");
3956
3957 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3958 Consumer.addKeywordResult("case");
3959 Consumer.addKeywordResult("default");
3960 }
3961 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003962 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003963 Consumer.addKeywordResult("namespace");
3964 Consumer.addKeywordResult("template");
3965 }
3966
3967 if (S && S->isClassScope()) {
3968 Consumer.addKeywordResult("explicit");
3969 Consumer.addKeywordResult("friend");
3970 Consumer.addKeywordResult("mutable");
3971 Consumer.addKeywordResult("private");
3972 Consumer.addKeywordResult("protected");
3973 Consumer.addKeywordResult("public");
3974 Consumer.addKeywordResult("virtual");
3975 }
3976 }
3977
David Blaikie4e4d0842012-03-11 07:00:24 +00003978 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003979 Consumer.addKeywordResult("using");
3980
Richard Smith80ad52f2013-01-02 11:42:31 +00003981 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003982 Consumer.addKeywordResult("static_assert");
3983 }
3984 }
3985}
3986
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003987static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3988 TypoCorrection &Candidate) {
3989 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3990 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3991}
3992
Richard Smithd67679d2013-08-20 20:35:18 +00003993/// \brief Check whether the declarations found for a typo correction are
3994/// visible, and if none of them are, convert the correction to an 'import
3995/// a module' correction.
3996static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3997 DeclarationName TypoName) {
3998 if (TC.begin() == TC.end())
3999 return;
4000
4001 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4002
4003 for (/**/; DI != DE; ++DI)
4004 if (!LookupResult::isVisible(SemaRef, *DI))
4005 break;
4006 // Nothing to do if all decls are visible.
4007 if (DI == DE)
4008 return;
4009
4010 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4011 bool AnyVisibleDecls = !NewDecls.empty();
4012
4013 for (/**/; DI != DE; ++DI) {
4014 NamedDecl *VisibleDecl = *DI;
4015 if (!LookupResult::isVisible(SemaRef, *DI))
4016 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
4017
4018 if (VisibleDecl) {
4019 if (!AnyVisibleDecls) {
4020 // Found a visible decl, discard all hidden ones.
4021 AnyVisibleDecls = true;
4022 NewDecls.clear();
4023 }
4024 NewDecls.push_back(VisibleDecl);
4025 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4026 NewDecls.push_back(*DI);
4027 }
4028
4029 if (NewDecls.empty())
4030 TC = TypoCorrection();
4031 else {
4032 TC.setCorrectionDecls(NewDecls);
4033 TC.setRequiresImport(!AnyVisibleDecls);
4034 }
4035}
4036
Douglas Gregor546be3c2009-12-30 17:04:44 +00004037/// \brief Try to "correct" a typo in the source code by finding
4038/// visible declarations whose names are similar to the name that was
4039/// present in the source code.
4040///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004041/// \param TypoName the \c DeclarationNameInfo structure that contains
4042/// the name that was present in the source code along with its location.
4043///
4044/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00004045///
4046/// \param S the scope in which name lookup occurs.
4047///
4048/// \param SS the nested-name-specifier that precedes the name we're
4049/// looking for, if present.
4050///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004051/// \param CCC A CorrectionCandidateCallback object that provides further
4052/// validation of typo correction candidates. It also provides flags for
4053/// determining the set of keywords permitted.
4054///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00004055/// \param MemberContext if non-NULL, the context in which to look for
4056/// a member access expression.
4057///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004058/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00004059/// the nested-name-specifier SS.
4060///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004061/// \param OPT when non-NULL, the search for visible declarations will
4062/// also walk the protocols in the qualified interfaces of \p OPT.
4063///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004064/// \returns a \c TypoCorrection containing the corrected name if the typo
4065/// along with information such as the \c NamedDecl where the corrected name
4066/// was declared, and any additional \c NestedNameSpecifier needed to access
4067/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4068TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4069 Sema::LookupNameKind LookupKind,
4070 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004071 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004072 DeclContext *MemberContext,
4073 bool EnteringContext,
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004074 const ObjCObjectPointerType *OPT,
4075 bool RecordFailure) {
Kaelyn Uhrain70571f42013-08-12 19:54:38 +00004076 // Always let the ExternalSource have the first chance at correction, even
4077 // if we would otherwise have given up.
4078 if (ExternalSource) {
4079 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4080 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
4081 return Correction;
4082 }
4083
Richard Smith9bd3cdc2013-09-12 23:28:08 +00004084 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4085 DisableTypoCorrection)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004086 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004087
Francois Pichet4d604d62011-12-03 15:55:29 +00004088 // In Microsoft mode, don't perform typo correction in a template member
4089 // function dependent context because it interferes with the "lookup into
4090 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00004091 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00004092 isa<CXXMethodDecl>(CurContext))
4093 return TypoCorrection();
4094
Douglas Gregor546be3c2009-12-30 17:04:44 +00004095 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004096 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004097 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004098 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004099
4100 // If the scope specifier itself was invalid, don't try to correct
4101 // typos.
4102 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004103 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004104
4105 // Never try to correct typos during template deduction or
4106 // instantiation.
4107 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004108 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004109
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00004110 // Don't try to correct 'super'.
4111 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4112 return TypoCorrection();
4113
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004114 // Abort if typo correction already failed for this specific typo.
4115 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4116 if (locs != TypoCorrectionFailures.end() &&
Aaron Ballman6dfc04b2013-10-05 19:56:07 +00004117 locs->second.count(TypoName.getLoc()))
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004118 return TypoCorrection();
4119
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004120 // Don't try to correct the identifier "vector" when in AltiVec mode.
4121 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4122 // remove this workaround.
4123 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4124 return TypoCorrection();
4125
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004126 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004127
4128 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004129
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004130 // If a callback object considers an empty typo correction candidate to be
4131 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004132 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004133 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004134
Douglas Gregoraaf87162010-04-14 20:04:41 +00004135 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004136 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004137 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004138 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004139 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004140
4141 // Look in qualified interfaces.
4142 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004143 for (ObjCObjectPointerType::qual_iterator
4144 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004145 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004146 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004147 }
4148 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004149 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4150 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004151 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004153 // Provide a stop gap for files that are just seriously broken. Trying
4154 // to correct all typos can turn into a HUGE performance penalty, causing
4155 // some files to take minutes to get rejected by the parser.
4156 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004157 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004158 ++TyposCorrected;
4159
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004160 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00004161 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004162 IsUnqualifiedLookup = true;
4163 UnqualifiedTyposCorrectedMap::iterator Cached
4164 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004165 if (Cached != UnqualifiedTyposCorrected.end()) {
4166 // Add the cached value, unless it's a keyword or fails validation. In the
4167 // keyword case, we'll end up adding the keyword below.
4168 if (Cached->second) {
4169 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004170 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004171 Consumer.addCorrection(Cached->second);
4172 } else {
4173 // Only honor no-correction cache hits when a callback that will validate
4174 // correction candidates is not being used.
4175 if (!ValidatingCallback)
4176 return TypoCorrection();
4177 }
4178 }
4179 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004180 // Provide a stop gap for files that are just seriously broken. Trying
4181 // to correct all typos can turn into a HUGE performance penalty, causing
4182 // some files to take minutes to get rejected by the parser.
4183 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004184 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004185 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004186 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004187
Douglas Gregor01798682012-03-26 16:54:18 +00004188 // Determine whether we are going to search in the various namespaces for
4189 // corrections.
4190 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00004191 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00004192 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Richard Smithd67679d2013-08-20 20:35:18 +00004193 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004194 // adding or changing the nested name specifier.
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004195 unsigned TypoLen = Typo->getName().size();
4196 bool AllowOnlyNNSChanges = TypoLen < 3;
4197
Douglas Gregor01798682012-03-26 16:54:18 +00004198 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004199 // For unqualified lookup, look through all of the names that we have
4200 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004201 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004202 for (IdentifierTable::iterator I = Context.Idents.begin(),
4203 IEnd = Context.Idents.end();
4204 I != IEnd; ++I)
4205 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004206
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004207 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004208 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004209 if (IdentifierInfoLookup *External
4210 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00004211 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004212 do {
4213 StringRef Name = Iter->Next();
4214 if (Name.empty())
4215 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00004216
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004217 Consumer.FoundName(Name);
4218 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00004219 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004220 }
4221
Richard Smith0f4b5be2012-06-08 21:35:42 +00004222 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223
Douglas Gregoraaf87162010-04-14 20:04:41 +00004224 // If we haven't found anything, we're done.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004225 if (Consumer.empty())
4226 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4227 IsUnqualifiedLookup);
Douglas Gregor546be3c2009-12-30 17:04:44 +00004228
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004229 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4230 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004231 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004232 if (ED > 0 && TypoLen / ED < 3)
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004233 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4234 IsUnqualifiedLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004235
Douglas Gregor01798682012-03-26 16:54:18 +00004236 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4237 // to search those namespaces.
4238 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004239 // Load any externally-known namespaces.
4240 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004241 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004242 LoadedExternalKnownNamespaces = true;
4243 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4244 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4245 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4246 }
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004247
4248 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004249 KNI = KnownNamespaces.begin(),
4250 KNIEnd = KnownNamespaces.end();
4251 KNI != KNIEnd; ++KNI)
4252 Namespaces.AddNamespace(KNI->first);
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004253
4254 for (ASTContext::type_iterator TI = Context.types_begin(),
4255 TIEnd = Context.types_end();
4256 TI != TIEnd; ++TI) {
4257 if (CXXRecordDecl *CD = (*TI)->getAsCXXRecordDecl()) {
4258 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4259 !CD->isUnion())
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004260 Namespaces.AddRecord(CD->getCanonicalDecl());
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004261 }
4262 }
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004263 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004264
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004265 // Weed out any names that could not be found by name lookup or, if a
4266 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004267 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004268 LookupResult TmpRes(*this, TypoName, LookupKind);
4269 TmpRes.suppressDiagnostics();
4270 while (!Consumer.empty()) {
4271 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004272 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4273 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004274 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004275 // If we only want nested name specifier corrections, ignore potential
4276 // corrections that have a different base identifier from the typo.
4277 if (AllowOnlyNNSChanges &&
4278 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4279 TypoCorrectionConsumer::result_iterator Prev = I;
4280 ++I;
4281 DI->second.erase(Prev);
4282 continue;
4283 }
4284
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004285 // If the item already has been looked up or is a keyword, keep it.
4286 // If a validator callback object was given, drop the correction
4287 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004288 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00004289 for (TypoResultList::iterator RI = I->second.begin();
4290 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004291 TypoResultList::iterator Prev = RI;
4292 ++RI;
4293 if (Prev->isResolved()) {
4294 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00004295 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004296 else
4297 Viable = true;
4298 }
4299 }
4300 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004301 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004302 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004303 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004304 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004305 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00004306 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004307 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004309 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004310 TypoCorrection &Candidate = I->second.front();
4311 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004312 DeclContext *TempMemberContext = MemberContext;
4313 CXXScopeSpec *TempSS = SS;
4314retry_lookup:
4315 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4316 TempMemberContext, EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00004317 CCC.IsObjCIvarLookup,
4318 Name == TypoName.getName() &&
4319 !Candidate.WillReplaceSpecifier());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004320
4321 switch (TmpRes.getResultKind()) {
4322 case LookupResult::NotFound:
4323 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004324 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004325 if (TempSS) {
4326 // Immediately retry the lookup without the given CXXScopeSpec
4327 TempSS = NULL;
4328 Candidate.WillReplaceSpecifier(true);
4329 goto retry_lookup;
4330 }
4331 if (TempMemberContext) {
4332 if (SS && !TempSS)
4333 TempSS = SS;
4334 TempMemberContext = NULL;
4335 goto retry_lookup;
4336 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004337 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004338 // We didn't find this name in our scope, or didn't like what we found;
4339 // ignore it.
4340 {
4341 TypoCorrectionConsumer::result_iterator Next = I;
4342 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004343 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004344 I = Next;
4345 }
4346 break;
4347
4348 case LookupResult::Ambiguous:
4349 // We don't deal with ambiguities.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004350 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004351
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004352 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004353 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004354 // Store all of the Decls for overloaded symbols
4355 for (LookupResult::iterator TRD = TmpRes.begin(),
4356 TRDEnd = TmpRes.end();
4357 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004358 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004359 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004360 if (!isCandidateViable(CCC, Candidate)) {
4361 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004362 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004363 }
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004364 break;
4365 }
4366
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004367 case LookupResult::Found: {
4368 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004369 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004370 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004371 if (!isCandidateViable(CCC, Candidate)) {
4372 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004373 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004374 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004375 break;
4376 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004377
4378 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004380
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004381 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004382 Consumer.erase(DI);
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004383 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004384 // If there are results in the closest possible bucket, stop
4385 break;
4386
4387 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004388 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004389 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004390 for (SmallVector<TypoCorrection,
4391 16>::iterator QRI = QualifiedResults.begin(),
4392 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004393 QRI != QRIEnd; ++QRI) {
4394 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4395 NIEnd = Namespaces.end();
4396 NI != NIEnd; ++NI) {
4397 DeclContext *Ctx = NI->DeclCtx;
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004398 const Type *NSType = NI->NameSpecifier->getAsType();
4399
4400 // If the current NestedNameSpecifier refers to a class and the
4401 // current correction candidate is the name of that class, then skip
4402 // it as it is unlikely a qualified version of the class' constructor
4403 // is an appropriate correction.
4404 if (CXXRecordDecl *NSDecl =
4405 NSType ? NSType->getAsCXXRecordDecl() : 0) {
4406 if (NSDecl->getIdentifier() == QRI->getCorrectionAsIdentifierInfo())
4407 continue;
4408 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004409
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004410 TypoCorrection TC(*QRI);
4411 TC.ClearCorrectionDecls();
4412 TC.setCorrectionSpecifier(NI->NameSpecifier);
4413 TC.setQualifierDistance(NI->EditDistance);
4414 TC.setCallbackDistance(0); // Reset the callback distance
4415
4416 // If the current correction candidate and namespace combination are
4417 // too far away from the original typo based on the normalized edit
4418 // distance, then skip performing a qualified name lookup.
4419 unsigned TmpED = TC.getEditDistance(true);
4420 if (QRI->getCorrectionAsIdentifierInfo() != Typo &&
4421 TmpED && TypoLen / TmpED < 3)
4422 continue;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004423
4424 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004425 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004426 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4427
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004428 // Any corrections added below will be validated in subsequent
4429 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004430 switch (TmpRes.getResultKind()) {
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004431 case LookupResult::Found:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004432 case LookupResult::FoundOverloaded: {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004433 for (LookupResult::iterator TRD = TmpRes.begin(),
4434 TRDEnd = TmpRes.end();
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004435 TRD != TRDEnd; ++TRD) {
4436 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4437 NSType ? NSType->getAsCXXRecordDecl() : 0,
Eli Friedman91d3f332013-10-01 02:44:48 +00004438 TRD.getPair()) == AR_accessible)
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004439 TC.addCorrectionDecl(*TRD);
4440 }
4441 if (TC.isResolved())
4442 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004443 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004444 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004445 case LookupResult::NotFound:
4446 case LookupResult::NotFoundInCurrentInstantiation:
4447 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004448 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004449 break;
4450 }
4451 }
4452 }
4453 }
4454
4455 QualifiedResults.clear();
4456 }
4457
4458 // No corrections remain...
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004459 if (Consumer.empty())
4460 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004461
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004462 TypoResultsMap &BestResults = Consumer.getBestResults();
4463 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004464
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004465 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004466 // If this was an unqualified lookup and we believe the callback
4467 // object wouldn't have filtered out possible corrections, note
4468 // that no correction was found.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004469 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4470 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004471 }
4472
Douglas Gregore24b5752010-10-14 20:34:08 +00004473 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004474 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004475 const TypoResultList &CorrectionList = BestResults.begin()->second;
4476 const TypoCorrection &Result = CorrectionList.front();
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004477 if (CorrectionList.size() != 1)
4478 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004479
Douglas Gregor53e4b552010-10-26 17:18:00 +00004480 // Don't correct to a keyword that's the same as the typo; the keyword
4481 // wasn't actually in scope.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004482 if (ED == 0 && Result.isKeyword())
4483 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004484
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004485 // Record the correction for unqualified lookup.
4486 if (IsUnqualifiedLookup)
4487 UnqualifiedTyposCorrected[Typo] = Result;
4488
David Blaikie6952c012012-10-12 20:00:44 +00004489 TypoCorrection TC = Result;
4490 TC.setCorrectionRange(SS, TypoName);
Richard Smithd67679d2013-08-20 20:35:18 +00004491 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie6952c012012-10-12 20:00:44 +00004492 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004493 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004494 else if (BestResults.size() > 1
4495 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4496 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4497 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4498 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004499 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004500 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004501 // Prefer 'super' when we're completing in a message-receiver
4502 // context.
4503
4504 // Don't correct to a keyword that's the same as the typo; the keyword
4505 // wasn't actually in scope.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004506 if (ED == 0)
4507 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004509 // Record the correction for unqualified lookup.
4510 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004511 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512
David Blaikie6952c012012-10-12 20:00:44 +00004513 TypoCorrection TC = BestResults["super"].front();
4514 TC.setCorrectionRange(SS, TypoName);
4515 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004516 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004517
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004518 // If this was an unqualified lookup and we believe the callback object did
4519 // not filter out possible corrections, note that no correction was found.
4520 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004521 (void)UnqualifiedTyposCorrected[Typo];
4522
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004523 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004524}
4525
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004526void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4527 if (!CDecl) return;
4528
4529 if (isKeyword())
4530 CorrectionDecls.clear();
4531
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004532 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004533
4534 if (!CorrectionName)
4535 CorrectionName = CDecl->getDeclName();
4536}
4537
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004538std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4539 if (CorrectionNameSpec) {
4540 std::string tmpBuffer;
4541 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4542 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikie17828ca2013-05-14 21:04:00 +00004543 PrefixOStream << CorrectionName;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004544 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004545 }
4546
4547 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004548}
Kaelyn Uhrain20a7cf42013-04-03 16:59:49 +00004549
4550bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4551 if (!candidate.isResolved())
4552 return true;
4553
4554 if (candidate.isKeyword())
4555 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4556 WantRemainingKeywords || WantObjCSuper;
4557
4558 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4559 CDeclEnd = candidate.end();
4560 CDecl != CDeclEnd; ++CDecl) {
4561 if (!isa<TypeDecl>(*CDecl))
4562 return true;
4563 }
4564
4565 return WantTypeSpecifiers;
4566}
Kaelyn Uhrain761695f2013-07-08 23:13:39 +00004567
4568FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4569 bool HasExplicitTemplateArgs)
4570 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
4571 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4572 WantRemainingKeywords = false;
4573}
4574
4575bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4576 if (!candidate.getCorrectionDecl())
4577 return candidate.isKeyword();
4578
4579 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4580 DIEnd = candidate.end();
4581 DI != DIEnd; ++DI) {
4582 FunctionDecl *FD = 0;
4583 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4584 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4585 FD = FTD->getTemplatedDecl();
4586 if (!HasExplicitTemplateArgs && !FD) {
4587 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4588 // If the Decl is neither a function nor a template function,
4589 // determine if it is a pointer or reference to a function. If so,
4590 // check against the number of arguments expected for the pointee.
4591 QualType ValType = cast<ValueDecl>(ND)->getType();
4592 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4593 ValType = ValType->getPointeeType();
4594 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4595 if (FPT->getNumArgs() == NumArgs)
4596 return true;
4597 }
4598 }
4599 if (FD && FD->getNumParams() >= NumArgs &&
4600 FD->getMinRequiredArguments() <= NumArgs)
4601 return true;
4602 }
4603 return false;
4604}
Richard Smith2d670972013-08-17 00:46:16 +00004605
4606void Sema::diagnoseTypo(const TypoCorrection &Correction,
4607 const PartialDiagnostic &TypoDiag,
4608 bool ErrorRecovery) {
4609 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4610 ErrorRecovery);
4611}
4612
Richard Smithd67679d2013-08-20 20:35:18 +00004613/// Find which declaration we should import to provide the definition of
4614/// the given declaration.
4615static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4616 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4617 return VD->getDefinition();
4618 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4619 return FD->isDefined(FD) ? FD : 0;
4620 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4621 return TD->getDefinition();
4622 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4623 return ID->getDefinition();
4624 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4625 return PD->getDefinition();
4626 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4627 return getDefinitionToImport(TD->getTemplatedDecl());
4628 return 0;
4629}
4630
Richard Smith2d670972013-08-17 00:46:16 +00004631/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4632/// itself to allow external validation of the result, etc.
4633///
4634/// \param Correction The result of performing typo correction.
4635/// \param TypoDiag The diagnostic to produce. This will have the corrected
4636/// string added to it (and usually also a fixit).
4637/// \param PrevNote A note to use when indicating the location of the entity to
4638/// which we are correcting. Will have the correction string added to it.
4639/// \param ErrorRecovery If \c true (the default), the caller is going to
4640/// recover from the typo as if the corrected string had been typed.
4641/// In this case, \c PDiag must be an error, and we will attach a fixit
4642/// to it.
4643void Sema::diagnoseTypo(const TypoCorrection &Correction,
4644 const PartialDiagnostic &TypoDiag,
4645 const PartialDiagnostic &PrevNote,
4646 bool ErrorRecovery) {
4647 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4648 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4649 FixItHint FixTypo = FixItHint::CreateReplacement(
4650 Correction.getCorrectionRange(), CorrectedStr);
4651
Richard Smithd67679d2013-08-20 20:35:18 +00004652 // Maybe we're just missing a module import.
4653 if (Correction.requiresImport()) {
4654 NamedDecl *Decl = Correction.getCorrectionDecl();
4655 assert(Decl && "import required but no declaration to import");
4656
4657 // Suggest importing a module providing the definition of this entity, if
4658 // possible.
4659 const NamedDecl *Def = getDefinitionToImport(Decl);
4660 if (!Def)
4661 Def = Decl;
4662 Module *Owner = Def->getOwningModule();
4663 assert(Owner && "definition of hidden declaration is not in a module");
4664
4665 Diag(Correction.getCorrectionRange().getBegin(),
4666 diag::err_module_private_declaration)
4667 << Def << Owner->getFullModuleName();
4668 Diag(Def->getLocation(), diag::note_previous_declaration);
4669
4670 // Recover by implicitly importing this module.
4671 if (!isSFINAEContext() && ErrorRecovery)
4672 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4673 Owner);
4674 return;
4675 }
4676
Richard Smith2d670972013-08-17 00:46:16 +00004677 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4678 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4679
4680 NamedDecl *ChosenDecl =
4681 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4682 if (PrevNote.getDiagID() && ChosenDecl)
4683 Diag(ChosenDecl->getLocation(), PrevNote)
4684 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4685}