blob: f18b6ecdfe41ba24ecf67e1f7a1d3d25aa954d40 [file] [log] [blame]
Douglas Gregor34074322009-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 Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
Alexis Hunt4ac55e32011-06-04 04:32:43 +000017#include "clang/Sema/Overload.h"
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
John McCallcc14d1f2010-08-24 08:50:51 +000019#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
John McCall19c1bfd2010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Axel Naumann016538a2011-02-24 16:47:47 +000022#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregorc2fa1692011-06-28 16:20:02 +000023#include "clang/Sema/TypoCorrection.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000024#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000025#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/AST/Decl.h"
27#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000029#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000030#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000031#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000033#include "clang/Basic/LangOptions.h"
John McCalla1e130b2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor34074322009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000036#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000037#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000038#include "llvm/ADT/TinyPtrVector.h"
John McCall6538c932009-10-10 05:48:19 +000039#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000040#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000041#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000042#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000043#include <vector>
44#include <iterator>
45#include <utility>
46#include <algorithm>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000047#include <map>
Douglas Gregor34074322009-01-14 22:20:51 +000048
49using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000050using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000051
John McCallf6c8a4e2009-11-10 07:01:13 +000052namespace {
53 class UnqualUsingEntry {
54 const DeclContext *Nominated;
55 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000056
John McCallf6c8a4e2009-11-10 07:01:13 +000057 public:
58 UnqualUsingEntry(const DeclContext *Nominated,
59 const DeclContext *CommonAncestor)
60 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
61 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000062
John McCallf6c8a4e2009-11-10 07:01:13 +000063 const DeclContext *getCommonAncestor() const {
64 return CommonAncestor;
65 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000066
John McCallf6c8a4e2009-11-10 07:01:13 +000067 const DeclContext *getNominatedNamespace() const {
68 return Nominated;
69 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000070
John McCallf6c8a4e2009-11-10 07:01:13 +000071 // Sort by the pointer value of the common ancestor.
72 struct Comparator {
73 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
74 return L.getCommonAncestor() < R.getCommonAncestor();
75 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000076
John McCallf6c8a4e2009-11-10 07:01:13 +000077 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
78 return E.getCommonAncestor() < DC;
79 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000080
John McCallf6c8a4e2009-11-10 07:01:13 +000081 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
82 return DC < E.getCommonAncestor();
83 }
84 };
85 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000086
John McCallf6c8a4e2009-11-10 07:01:13 +000087 /// A collection of using directives, as used by C++ unqualified
88 /// lookup.
89 class UnqualUsingDirectiveSet {
90 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000091
John McCallf6c8a4e2009-11-10 07:01:13 +000092 ListTy list;
93 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
John McCallf6c8a4e2009-11-10 07:01:13 +000095 public:
96 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000097
John McCallf6c8a4e2009-11-10 07:01:13 +000098 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000099 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 // During unqualified name lookup, the names appear as if they
101 // were declared in the nearest enclosing namespace which contains
102 // both the using-directive and the nominated namespace.
103 DeclContext *InnermostFileDC
104 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
105 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000106
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000108 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
109 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
110 visit(Ctx, EffectiveDC);
111 } else {
112 Scope::udir_iterator I = S->using_directives_begin(),
113 End = S->using_directives_end();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000114
John McCallf6c8a4e2009-11-10 07:01:13 +0000115 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000116 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000117 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000118 }
119 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000120
121 // Visits a context and collect all of its using directives
122 // recursively. Treats all using directives as if they were
123 // declared in the context.
124 //
125 // A given context is only every visited once, so it is important
126 // that contexts be visited from the inside out in order to get
127 // the effective DCs right.
128 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
129 if (!visited.insert(DC))
130 return;
131
132 addUsingDirectives(DC, EffectiveDC);
133 }
134
135 // Visits a using directive and collects all of its using
136 // directives recursively. Treats all using directives as if they
137 // were declared in the effective DC.
138 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
139 DeclContext *NS = UD->getNominatedNamespace();
140 if (!visited.insert(NS))
141 return;
142
143 addUsingDirective(UD, EffectiveDC);
144 addUsingDirectives(NS, EffectiveDC);
145 }
146
147 // Adds all the using directives in a context (and those nominated
148 // by its using directives, transitively) as if they appeared in
149 // the given effective context.
150 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
151 llvm::SmallVector<DeclContext*,4> queue;
152 while (true) {
153 DeclContext::udir_iterator I, End;
154 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
155 UsingDirectiveDecl *UD = *I;
156 DeclContext *NS = UD->getNominatedNamespace();
157 if (visited.insert(NS)) {
158 addUsingDirective(UD, EffectiveDC);
159 queue.push_back(NS);
160 }
161 }
162
163 if (queue.empty())
164 return;
165
166 DC = queue.back();
167 queue.pop_back();
168 }
169 }
170
171 // Add a using directive as if it had been declared in the given
172 // context. This helps implement C++ [namespace.udir]p3:
173 // The using-directive is transitive: if a scope contains a
174 // using-directive that nominates a second namespace that itself
175 // contains using-directives, the effect is as if the
176 // using-directives from the second namespace also appeared in
177 // the first.
178 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
179 // Find the common ancestor between the effective context and
180 // the nominated namespace.
181 DeclContext *Common = UD->getNominatedNamespace();
182 while (!Common->Encloses(EffectiveDC))
183 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000184 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000185
John McCallf6c8a4e2009-11-10 07:01:13 +0000186 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
187 }
188
189 void done() {
190 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
191 }
192
John McCallf6c8a4e2009-11-10 07:01:13 +0000193 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000194
John McCallf6c8a4e2009-11-10 07:01:13 +0000195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
197
198 std::pair<const_iterator,const_iterator>
199 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000200 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000201 UnqualUsingEntry::Comparator());
202 }
203 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000204}
205
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206// Retrieve the set of identifier namespaces that correspond to a
207// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000208static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
209 bool CPlusPlus,
210 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000211 unsigned IDNS = 0;
212 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000213 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000214 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000215 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000217 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000219 if (Redeclaration)
220 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000221 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000222 break;
223
John McCallb9467b62010-04-24 01:30:58 +0000224 case Sema::LookupOperatorName:
225 // Operator lookup is its own crazy thing; it is not the same
226 // as (e.g.) looking up an operator name for redeclaration.
227 assert(!Redeclaration && "cannot do redeclaration operator lookup");
228 IDNS = Decl::IDNS_NonMemberOperator;
229 break;
230
Douglas Gregor889ceb72009-02-03 19:21:40 +0000231 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000232 if (CPlusPlus) {
233 IDNS = Decl::IDNS_Type;
234
235 // When looking for a redeclaration of a tag name, we add:
236 // 1) TagFriend to find undeclared friend decls
237 // 2) Namespace because they can't "overload" with tag decls.
238 // 3) Tag because it includes class templates, which can't
239 // "overload" with tag decls.
240 if (Redeclaration)
241 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
242 } else {
243 IDNS = Decl::IDNS_Tag;
244 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000245 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000246 case Sema::LookupLabel:
247 IDNS = Decl::IDNS_Label;
248 break;
249
Douglas Gregor889ceb72009-02-03 19:21:40 +0000250 case Sema::LookupMemberName:
251 IDNS = Decl::IDNS_Member;
252 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000253 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000254 break;
255
256 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000257 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
258 break;
259
Douglas Gregor889ceb72009-02-03 19:21:40 +0000260 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000263
John McCall84d87672009-12-10 09:41:52 +0000264 case Sema::LookupUsingDeclName:
265 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
266 | Decl::IDNS_Member | Decl::IDNS_Using;
267 break;
268
Douglas Gregor79947a22009-04-24 00:11:27 +0000269 case Sema::LookupObjCProtocolName:
270 IDNS = Decl::IDNS_ObjCProtocol;
271 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000272
Douglas Gregor39982192010-08-15 06:18:01 +0000273 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000275 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
276 | Decl::IDNS_Type;
277 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000278 }
279 return IDNS;
280}
281
John McCallea305ed2009-12-18 10:40:03 +0000282void LookupResult::configure() {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000283 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000284 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000285
286 // If we're looking for one of the allocation or deallocation
287 // operators, make sure that the implicitly-declared new and delete
288 // operators can be found.
289 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000290 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000291 case OO_New:
292 case OO_Delete:
293 case OO_Array_New:
294 case OO_Array_Delete:
295 SemaRef.DeclareGlobalNewDelete();
296 break;
297
298 default:
299 break;
300 }
301 }
John McCallea305ed2009-12-18 10:40:03 +0000302}
303
John McCall19c1bfd2010-08-25 05:32:35 +0000304void LookupResult::sanity() const {
305 assert(ResultKind != NotFound || Decls.size() == 0);
306 assert(ResultKind != Found || Decls.size() == 1);
307 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
308 (Decls.size() == 1 &&
309 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
310 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
311 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000312 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
313 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000314 assert((Paths != NULL) == (ResultKind == Ambiguous &&
315 (Ambiguity == AmbiguousBaseSubobjectTypes ||
316 Ambiguity == AmbiguousBaseSubobjects)));
317}
John McCall19c1bfd2010-08-25 05:32:35 +0000318
John McCall9f3059a2009-10-09 21:13:30 +0000319// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000320void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000321 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000322}
323
John McCall283b9012009-11-22 00:44:51 +0000324/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000325void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000326 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327
John McCall9f3059a2009-10-09 21:13:30 +0000328 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000329 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000330 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000331 return;
332 }
333
John McCall283b9012009-11-22 00:44:51 +0000334 // If there's a single decl, we need to examine it to decide what
335 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000336 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000337 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
338 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000339 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000340 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000341 ResultKind = FoundUnresolvedValue;
342 return;
343 }
John McCall9f3059a2009-10-09 21:13:30 +0000344
John McCall6538c932009-10-10 05:48:19 +0000345 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000346 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000347
John McCall9f3059a2009-10-09 21:13:30 +0000348 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000349 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000350
John McCall9f3059a2009-10-09 21:13:30 +0000351 bool Ambiguous = false;
352 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000353 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000354
355 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000356
John McCall9f3059a2009-10-09 21:13:30 +0000357 unsigned I = 0;
358 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000359 NamedDecl *D = Decls[I]->getUnderlyingDecl();
360 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000361
Douglas Gregor13e65872010-08-11 14:45:53 +0000362 // Redeclarations of types via typedef can occur both within a scope
363 // and, through using declarations and directives, across scopes. There is
364 // no ambiguity if they all refer to the same type, so unique based on the
365 // canonical type.
366 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
367 if (!TD->getDeclContext()->isRecord()) {
368 QualType T = SemaRef.Context.getTypeDeclType(TD);
369 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
370 // The type is not unique; pull something off the back and continue
371 // at this index.
372 Decls[I] = Decls[--N];
373 continue;
374 }
375 }
376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377
John McCallf0f1cf02009-11-17 07:50:12 +0000378 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000379 // If it's not unique, pull something off the back (and
380 // continue at this index).
381 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000382 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000383 }
384
Douglas Gregor13e65872010-08-11 14:45:53 +0000385 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000386
Douglas Gregor13e65872010-08-11 14:45:53 +0000387 if (isa<UnresolvedUsingValueDecl>(D)) {
388 HasUnresolved = true;
389 } else if (isa<TagDecl>(D)) {
390 if (HasTag)
391 Ambiguous = true;
392 UniqueTagIndex = I;
393 HasTag = true;
394 } else if (isa<FunctionTemplateDecl>(D)) {
395 HasFunction = true;
396 HasFunctionTemplate = true;
397 } else if (isa<FunctionDecl>(D)) {
398 HasFunction = true;
399 } else {
400 if (HasNonFunction)
401 Ambiguous = true;
402 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000403 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000404 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000405 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000406
John McCall9f3059a2009-10-09 21:13:30 +0000407 // C++ [basic.scope.hiding]p2:
408 // A class name or enumeration name can be hidden by the name of
409 // an object, function, or enumerator declared in the same
410 // scope. If a class or enumeration name and an object, function,
411 // or enumerator are declared in the same scope (in any order)
412 // with the same name, the class or enumeration name is hidden
413 // wherever the object, function, or enumerator name is visible.
414 // But it's still an error if there are distinct tag types found,
415 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000416 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000417 (HasFunction || HasNonFunction || HasUnresolved)) {
418 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
419 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
420 Decls[UniqueTagIndex] = Decls[--N];
421 else
422 Ambiguous = true;
423 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000424
John McCall9f3059a2009-10-09 21:13:30 +0000425 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000426
John McCall80053822009-12-03 00:58:24 +0000427 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000428 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000429
John McCall9f3059a2009-10-09 21:13:30 +0000430 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000431 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000432 else if (HasUnresolved)
433 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000434 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000435 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000436 else
John McCall27b18f82009-11-17 02:14:36 +0000437 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000438}
439
John McCall5cebab12009-11-18 07:57:50 +0000440void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000441 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000442 DeclContext::lookup_iterator DI, DE;
443 for (I = P.begin(), E = P.end(); I != E; ++I)
444 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
445 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000446}
447
John McCall5cebab12009-11-18 07:57:50 +0000448void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000449 Paths = new CXXBasePaths;
450 Paths->swap(P);
451 addDeclsFromBasePaths(*Paths);
452 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000453 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000454}
455
John McCall5cebab12009-11-18 07:57:50 +0000456void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000457 Paths = new CXXBasePaths;
458 Paths->swap(P);
459 addDeclsFromBasePaths(*Paths);
460 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000461 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000462}
463
John McCall5cebab12009-11-18 07:57:50 +0000464void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000465 Out << Decls.size() << " result(s)";
466 if (isAmbiguous()) Out << ", ambiguous";
467 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
John McCall9f3059a2009-10-09 21:13:30 +0000469 for (iterator I = begin(), E = end(); I != E; ++I) {
470 Out << "\n";
471 (*I)->print(Out, 2);
472 }
473}
474
Douglas Gregord3a59182010-02-12 05:48:04 +0000475/// \brief Lookup a builtin function, when name lookup would otherwise
476/// fail.
477static bool LookupBuiltin(Sema &S, LookupResult &R) {
478 Sema::LookupNameKind NameKind = R.getLookupKind();
479
480 // If we didn't find a use of this identifier, and if the identifier
481 // corresponds to a compiler builtin, create the decl object for the builtin
482 // now, injecting it into translation unit scope, and return it.
483 if (NameKind == Sema::LookupOrdinaryName ||
484 NameKind == Sema::LookupRedeclarationWithLinkage) {
485 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
486 if (II) {
487 // If this is a builtin on this (or all) targets, create the decl.
488 if (unsigned BuiltinID = II->getBuiltinID()) {
489 // In C++, we don't have any predefined library functions like
490 // 'malloc'. Instead, we'll just error.
491 if (S.getLangOptions().CPlusPlus &&
492 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
493 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000494
495 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
496 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000497 R.isForRedeclaration(),
498 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000499 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000500 return true;
501 }
502
503 if (R.isForRedeclaration()) {
504 // If we're redeclaring this function anyway, forget that
505 // this was a builtin at all.
506 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
507 }
508
509 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000510 }
511 }
512 }
513
514 return false;
515}
516
Douglas Gregor7454c562010-07-02 20:37:36 +0000517/// \brief Determine whether we can declare a special member function within
518/// the class at this point.
519static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
520 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000521 // Don't do it if the class is invalid.
522 if (Class->isInvalidDecl())
523 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000524
Douglas Gregor7454c562010-07-02 20:37:36 +0000525 // We need to have a definition for the class.
526 if (!Class->getDefinition() || Class->isDependentContext())
527 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000528
Douglas Gregor7454c562010-07-02 20:37:36 +0000529 // We can't be in the middle of defining the class.
530 if (const RecordType *RecordTy
531 = Context.getTypeDeclType(Class)->getAs<RecordType>())
532 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor7454c562010-07-02 20:37:36 +0000534 return false;
535}
536
537void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000538 if (!CanDeclareSpecialMemberFunction(Context, Class))
539 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000540
541 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000542 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000543 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000544
Douglas Gregora6d69502010-07-02 23:41:54 +0000545 // If the copy constructor has not yet been declared, do so now.
546 if (!Class->hasDeclaredCopyConstructor())
547 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000548
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000549 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000550 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000551 DeclareImplicitCopyAssignment(Class);
552
Douglas Gregor7454c562010-07-02 20:37:36 +0000553 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000554 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000556}
557
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000559/// special member function.
560static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
561 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000562 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000563 case DeclarationName::CXXDestructorName:
564 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000566 case DeclarationName::CXXOperatorName:
567 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000569 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000573 return false;
574}
575
576/// \brief If there are any implicit member functions with the given name
577/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000579 DeclarationName Name,
580 const DeclContext *DC) {
581 if (!DC)
582 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000584 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000585 case DeclarationName::CXXConstructorName:
586 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000587 if (Record->getDefinition() &&
588 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Alexis Huntea6f0322011-05-11 22:34:38 +0000589 if (Record->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000590 S.DeclareImplicitDefaultConstructor(
591 const_cast<CXXRecordDecl *>(Record));
592 if (!Record->hasDeclaredCopyConstructor())
593 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
594 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000595 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000597 case DeclarationName::CXXDestructorName:
598 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
599 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
600 CanDeclareSpecialMemberFunction(S.Context, Record))
601 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000602 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000604 case DeclarationName::CXXOperatorName:
605 if (Name.getCXXOverloadedOperator() != OO_Equal)
606 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000608 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
609 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
610 CanDeclareSpecialMemberFunction(S.Context, Record))
611 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
612 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000613
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000614 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000616 }
617}
Douglas Gregor7454c562010-07-02 20:37:36 +0000618
John McCall9f3059a2009-10-09 21:13:30 +0000619// Adds all qualifying matches for a name within a decl context to the
620// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000621static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000622 bool Found = false;
623
Douglas Gregor7454c562010-07-02 20:37:36 +0000624 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000625 if (S.getLangOptions().CPlusPlus)
626 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
Douglas Gregor7454c562010-07-02 20:37:36 +0000628 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000629 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000630 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000631 NamedDecl *D = *I;
632 if (R.isAcceptableDecl(D)) {
633 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000634 Found = true;
635 }
636 }
John McCall9f3059a2009-10-09 21:13:30 +0000637
Douglas Gregord3a59182010-02-12 05:48:04 +0000638 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
639 return true;
640
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000641 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000642 != DeclarationName::CXXConversionFunctionName ||
643 R.getLookupName().getCXXNameType()->isDependentType() ||
644 !isa<CXXRecordDecl>(DC))
645 return Found;
646
647 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000648 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000649 // name lookup. Instead, any conversion function templates visible in the
650 // context of the use are considered. [...]
651 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
652 if (!Record->isDefinition())
653 return Found;
654
655 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000657 UEnd = Unresolved->end(); U != UEnd; ++U) {
658 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
659 if (!ConvTemplate)
660 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
Chandler Carruth3a693b72010-01-31 11:44:02 +0000662 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663 // add the conversion function template. When we deduce template
664 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000665 // type of the new declaration with the type of the function template.
666 if (R.isForRedeclaration()) {
667 R.addDecl(ConvTemplate);
668 Found = true;
669 continue;
670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000672 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000673 // [...] For each such operator, if argument deduction succeeds
674 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000675 // name lookup.
676 //
677 // When referencing a conversion function for any purpose other than
678 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000679 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000680 // specialization into the result set. We do this to avoid forcing all
681 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000682 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000683 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684
685 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000686 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
687 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000688
Chandler Carruth3a693b72010-01-31 11:44:02 +0000689 // Compute the type of the function that we would expect the conversion
690 // function to have, if it were to match the name given.
691 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000692 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
693 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000694 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000695 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000696 QualType ExpectedType
697 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000698 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
Chandler Carruth3a693b72010-01-31 11:44:02 +0000700 // Perform template argument deduction against the type that we would
701 // expect the function to have.
702 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
703 Specialization, Info)
704 == Sema::TDK_Success) {
705 R.addDecl(Specialization);
706 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000707 }
708 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709
John McCall9f3059a2009-10-09 21:13:30 +0000710 return Found;
711}
712
John McCallf6c8a4e2009-11-10 07:01:13 +0000713// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000714static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000716 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000717
718 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
719
John McCallf6c8a4e2009-11-10 07:01:13 +0000720 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000721 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000722
John McCallf6c8a4e2009-11-10 07:01:13 +0000723 // Perform direct name lookup into the namespaces nominated by the
724 // using directives whose common ancestor is this namespace.
725 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
726 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000727
John McCallf6c8a4e2009-11-10 07:01:13 +0000728 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000729 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000730 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000731
732 R.resolveKind();
733
734 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000735}
736
737static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000738 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000739 return Ctx->isFileContext();
740 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000741}
Douglas Gregored8f2882009-01-30 01:04:22 +0000742
Douglas Gregor66230062010-03-15 14:33:29 +0000743// Find the next outer declaration context from this scope. This
744// routine actually returns the semantic outer context, which may
745// differ from the lexical context (encoded directly in the Scope
746// stack) when we are parsing a member of a class template. In this
747// case, the second element of the pair will be true, to indicate that
748// name lookup should continue searching in this semantic context when
749// it leaves the current template parameter scope.
750static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
751 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
752 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000753 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000754 OuterS = OuterS->getParent()) {
755 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000756 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000757 break;
758 }
759 }
760
761 // C++ [temp.local]p8:
762 // In the definition of a member of a class template that appears
763 // outside of the namespace containing the class template
764 // definition, the name of a template-parameter hides the name of
765 // a member of this namespace.
766 //
767 // Example:
768 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769 // namespace N {
770 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000771 //
772 // template<class T> class B {
773 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000775 // }
776 //
777 // template<class C> void N::B<C>::f(C) {
778 // C b; // C is the template parameter, not N::C
779 // }
780 //
781 // In this example, the lexical context we return is the
782 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000783 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000784 !S->getParent()->isTemplateParamScope())
785 return std::make_pair(Lexical, false);
786
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000788 // For the example, this is the scope for the template parameters of
789 // template<class C>.
790 Scope *OutermostTemplateScope = S->getParent();
791 while (OutermostTemplateScope->getParent() &&
792 OutermostTemplateScope->getParent()->isTemplateParamScope())
793 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794
Douglas Gregor66230062010-03-15 14:33:29 +0000795 // Find the namespace context in which the original scope occurs. In
796 // the example, this is namespace N.
797 DeclContext *Semantic = DC;
798 while (!Semantic->isFileContext())
799 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800
Douglas Gregor66230062010-03-15 14:33:29 +0000801 // Find the declaration context just outside of the template
802 // parameter scope. This is the context in which the template is
803 // being lexically declaration (a namespace context). In the
804 // example, this is the global scope.
805 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
806 Lexical->Encloses(Semantic))
807 return std::make_pair(Semantic, true);
808
809 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000810}
811
John McCall27b18f82009-11-17 02:14:36 +0000812bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000813 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000814
815 DeclarationName Name = R.getLookupName();
816
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000817 // If this is the name of an implicitly-declared special member function,
818 // go through the scope stack to implicitly declare
819 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
820 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
821 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
822 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000825 // Implicitly declare member functions with the name we're looking for, if in
826 // fact we are in a scope where it matters.
827
Douglas Gregor889ceb72009-02-03 19:21:40 +0000828 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000829 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000830 I = IdResolver.begin(Name),
831 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000832
Douglas Gregor889ceb72009-02-03 19:21:40 +0000833 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000834 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000835 // ...During unqualified name lookup (3.4.1), the names appear as if
836 // they were declared in the nearest enclosing namespace which contains
837 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000838 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000839 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000840 //
841 // For example:
842 // namespace A { int i; }
843 // void foo() {
844 // int i;
845 // {
846 // using namespace A;
847 // ++i; // finds local 'i', A::i appears at global scope
848 // }
849 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000850 //
Douglas Gregor66230062010-03-15 14:33:29 +0000851 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000852 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000853 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
854
Douglas Gregor889ceb72009-02-03 19:21:40 +0000855 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000856 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000857 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000858 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000859 Found = true;
860 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000861 }
862 }
John McCall9f3059a2009-10-09 21:13:30 +0000863 if (Found) {
864 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000865 if (S->isClassScope())
866 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
867 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000868 return true;
869 }
870
Douglas Gregor66230062010-03-15 14:33:29 +0000871 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
872 S->getParent() && !S->getParent()->isTemplateParamScope()) {
873 // We've just searched the last template parameter scope and
874 // found nothing, so look into the the contexts between the
875 // lexical and semantic declaration contexts returned by
876 // findOuterContext(). This implements the name lookup behavior
877 // of C++ [temp.local]p8.
878 Ctx = OutsideOfTemplateParamDC;
879 OutsideOfTemplateParamDC = 0;
880 }
881
882 if (Ctx) {
883 DeclContext *OuterCtx;
884 bool SearchAfterTemplateScope;
885 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
886 if (SearchAfterTemplateScope)
887 OutsideOfTemplateParamDC = OuterCtx;
888
Douglas Gregorea166062010-03-15 15:26:48 +0000889 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000890 // We do not directly look into transparent contexts, since
891 // those entities will be found in the nearest enclosing
892 // non-transparent context.
893 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000894 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000895
896 // We do not look directly into function or method contexts,
897 // since all of the local variables and parameters of the
898 // function/method are present within the Scope.
899 if (Ctx->isFunctionOrMethod()) {
900 // If we have an Objective-C instance method, look for ivars
901 // in the corresponding interface.
902 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
903 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
904 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
905 ObjCInterfaceDecl *ClassDeclared;
906 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000907 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000908 ClassDeclared)) {
909 if (R.isAcceptableDecl(Ivar)) {
910 R.addDecl(Ivar);
911 R.resolveKind();
912 return true;
913 }
914 }
915 }
916 }
917
918 continue;
919 }
920
Douglas Gregor7f737c02009-09-10 16:57:35 +0000921 // Perform qualified name lookup into this context.
922 // FIXME: In some cases, we know that every name that could be found by
923 // this qualified name lookup will also be on the identifier chain. For
924 // example, inside a class without any base classes, we never need to
925 // perform qualified lookup because all of the members are on top of the
926 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000927 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000928 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000929 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000930 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000931 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000932
John McCallf6c8a4e2009-11-10 07:01:13 +0000933 // Stop if we ran out of scopes.
934 // FIXME: This really, really shouldn't be happening.
935 if (!S) return false;
936
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000937 // If we are looking for members, no need to look into global/namespace scope.
938 if (R.getLookupKind() == LookupMemberName)
939 return false;
940
Douglas Gregor700792c2009-02-05 19:25:20 +0000941 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000942 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000943 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000944 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
945 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000946
John McCallf6c8a4e2009-11-10 07:01:13 +0000947 UnqualUsingDirectiveSet UDirs;
948 UDirs.visitScopeChain(Initial, S);
949 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000950
Douglas Gregor700792c2009-02-05 19:25:20 +0000951 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000952 // Unqualified name lookup in C++ requires looking into scopes
953 // that aren't strictly lexical, and therefore we walk through the
954 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000955
Douglas Gregor889ceb72009-02-03 19:21:40 +0000956 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000957 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000958 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000959 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000960 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000961 // We found something. Look for anything else in our scope
962 // with this same name and in an acceptable identifier
963 // namespace, so that we can construct an overload set if we
964 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000965 Found = true;
966 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000967 }
968 }
969
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000970 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000971 R.resolveKind();
972 return true;
973 }
974
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000975 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
976 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
977 S->getParent() && !S->getParent()->isTemplateParamScope()) {
978 // We've just searched the last template parameter scope and
979 // found nothing, so look into the the contexts between the
980 // lexical and semantic declaration contexts returned by
981 // findOuterContext(). This implements the name lookup behavior
982 // of C++ [temp.local]p8.
983 Ctx = OutsideOfTemplateParamDC;
984 OutsideOfTemplateParamDC = 0;
985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000986
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000987 if (Ctx) {
988 DeclContext *OuterCtx;
989 bool SearchAfterTemplateScope;
990 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
991 if (SearchAfterTemplateScope)
992 OutsideOfTemplateParamDC = OuterCtx;
993
994 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
995 // We do not directly look into transparent contexts, since
996 // those entities will be found in the nearest enclosing
997 // non-transparent context.
998 if (Ctx->isTransparentContext())
999 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001000
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001001 // If we have a context, and it's not a context stashed in the
1002 // template parameter scope for an out-of-line definition, also
1003 // look into that context.
1004 if (!(Found && S && S->isTemplateParamScope())) {
1005 assert(Ctx->isFileContext() &&
1006 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001008 // Look into context considering using-directives.
1009 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1010 Found = true;
1011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001013 if (Found) {
1014 R.resolveKind();
1015 return true;
1016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001017
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001018 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1019 return false;
1020 }
1021 }
1022
Douglas Gregor3ce74932010-02-05 07:07:10 +00001023 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001024 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001025 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001026
John McCall9f3059a2009-10-09 21:13:30 +00001027 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001028}
1029
Douglas Gregor34074322009-01-14 22:20:51 +00001030/// @brief Perform unqualified name lookup starting from a given
1031/// scope.
1032///
1033/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1034/// used to find names within the current scope. For example, 'x' in
1035/// @code
1036/// int x;
1037/// int f() {
1038/// return x; // unqualified name look finds 'x' in the global scope
1039/// }
1040/// @endcode
1041///
1042/// Different lookup criteria can find different names. For example, a
1043/// particular scope can have both a struct and a function of the same
1044/// name, and each can be found by certain lookup criteria. For more
1045/// information about lookup criteria, see the documentation for the
1046/// class LookupCriteria.
1047///
1048/// @param S The scope from which unqualified name lookup will
1049/// begin. If the lookup criteria permits, name lookup may also search
1050/// in the parent scopes.
1051///
1052/// @param Name The name of the entity that we are searching for.
1053///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001054/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001055/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001056/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001057///
1058/// @returns The result of name lookup, which includes zero or more
1059/// declarations and possibly additional information used to diagnose
1060/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001061bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1062 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001063 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001064
John McCall27b18f82009-11-17 02:14:36 +00001065 LookupNameKind NameKind = R.getLookupKind();
1066
Douglas Gregor34074322009-01-14 22:20:51 +00001067 if (!getLangOptions().CPlusPlus) {
1068 // Unqualified name lookup in C/Objective-C is purely lexical, so
1069 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001070 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001071 // Find the nearest non-transparent declaration scope.
1072 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001073 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001074 static_cast<DeclContext *>(S->getEntity())
1075 ->isTransparentContext()))
1076 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001077 }
1078
John McCallea305ed2009-12-18 10:40:03 +00001079 unsigned IDNS = R.getIdentifierNamespace();
1080
Douglas Gregor34074322009-01-14 22:20:51 +00001081 // Scan up the scope chain looking for a decl that matches this
1082 // identifier that is in the appropriate namespace. This search
1083 // should not take long, as shadowing of names is uncommon, and
1084 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001085 bool LeftStartingScope = false;
1086
Douglas Gregored8f2882009-01-30 01:04:22 +00001087 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001088 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001089 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001090 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001091 if (NameKind == LookupRedeclarationWithLinkage) {
1092 // Determine whether this (or a previous) declaration is
1093 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001094 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001095 LeftStartingScope = true;
1096
1097 // If we found something outside of our starting scope that
1098 // does not have linkage, skip it.
1099 if (LeftStartingScope && !((*I)->hasLinkage()))
1100 continue;
1101 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001102 else if (NameKind == LookupObjCImplicitSelfParam &&
1103 !isa<ImplicitParamDecl>(*I))
1104 continue;
1105
John McCall9f3059a2009-10-09 21:13:30 +00001106 R.addDecl(*I);
1107
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001108 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001109 // If this declaration has the "overloadable" attribute, we
1110 // might have a set of overloaded functions.
1111
1112 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001113 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001114 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001115 S = S->getParent();
1116
1117 // Find the last declaration in this scope (with the same
1118 // name, naturally).
1119 IdentifierResolver::iterator LastI = I;
1120 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001121 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001122 break;
John McCall9f3059a2009-10-09 21:13:30 +00001123 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001124 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001125 }
1126
John McCall9f3059a2009-10-09 21:13:30 +00001127 R.resolveKind();
1128
1129 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001130 }
Douglas Gregor34074322009-01-14 22:20:51 +00001131 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001132 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001133 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001134 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001135 }
1136
1137 // If we didn't find a use of this identifier, and if the identifier
1138 // corresponds to a compiler builtin, create the decl object for the builtin
1139 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001140 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1141 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001142
Axel Naumann016538a2011-02-24 16:47:47 +00001143 // If we didn't find a use of this identifier, the ExternalSource
1144 // may be able to handle the situation.
1145 // Note: some lookup failures are expected!
1146 // See e.g. R.isForRedeclaration().
1147 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001148}
1149
John McCall6538c932009-10-10 05:48:19 +00001150/// @brief Perform qualified name lookup in the namespaces nominated by
1151/// using directives by the given context.
1152///
1153/// C++98 [namespace.qual]p2:
1154/// Given X::m (where X is a user-declared namespace), or given ::m
1155/// (where X is the global namespace), let S be the set of all
1156/// declarations of m in X and in the transitive closure of all
1157/// namespaces nominated by using-directives in X and its used
1158/// namespaces, except that using-directives are ignored in any
1159/// namespace, including X, directly containing one or more
1160/// declarations of m. No namespace is searched more than once in
1161/// the lookup of a name. If S is the empty set, the program is
1162/// ill-formed. Otherwise, if S has exactly one member, or if the
1163/// context of the reference is a using-declaration
1164/// (namespace.udecl), S is the required set of declarations of
1165/// m. Otherwise if the use of m is not one that allows a unique
1166/// declaration to be chosen from S, the program is ill-formed.
1167/// C++98 [namespace.qual]p5:
1168/// During the lookup of a qualified namespace member name, if the
1169/// lookup finds more than one declaration of the member, and if one
1170/// declaration introduces a class name or enumeration name and the
1171/// other declarations either introduce the same object, the same
1172/// enumerator or a set of functions, the non-type name hides the
1173/// class or enumeration name if and only if the declarations are
1174/// from the same namespace; otherwise (the declarations are from
1175/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001176static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001177 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001178 assert(StartDC->isFileContext() && "start context is not a file context");
1179
1180 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1181 DeclContext::udir_iterator E = StartDC->using_directives_end();
1182
1183 if (I == E) return false;
1184
1185 // We have at least added all these contexts to the queue.
1186 llvm::DenseSet<DeclContext*> Visited;
1187 Visited.insert(StartDC);
1188
1189 // We have not yet looked into these namespaces, much less added
1190 // their "using-children" to the queue.
1191 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1192
1193 // We have already looked into the initial namespace; seed the queue
1194 // with its using-children.
1195 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001196 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001197 if (Visited.insert(ND).second)
1198 Queue.push_back(ND);
1199 }
1200
1201 // The easiest way to implement the restriction in [namespace.qual]p5
1202 // is to check whether any of the individual results found a tag
1203 // and, if so, to declare an ambiguity if the final result is not
1204 // a tag.
1205 bool FoundTag = false;
1206 bool FoundNonTag = false;
1207
John McCall5cebab12009-11-18 07:57:50 +00001208 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001209
1210 bool Found = false;
1211 while (!Queue.empty()) {
1212 NamespaceDecl *ND = Queue.back();
1213 Queue.pop_back();
1214
1215 // We go through some convolutions here to avoid copying results
1216 // between LookupResults.
1217 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001218 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001219 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001220
1221 if (FoundDirect) {
1222 // First do any local hiding.
1223 DirectR.resolveKind();
1224
1225 // If the local result is a tag, remember that.
1226 if (DirectR.isSingleTagDecl())
1227 FoundTag = true;
1228 else
1229 FoundNonTag = true;
1230
1231 // Append the local results to the total results if necessary.
1232 if (UseLocal) {
1233 R.addAllDecls(LocalR);
1234 LocalR.clear();
1235 }
1236 }
1237
1238 // If we find names in this namespace, ignore its using directives.
1239 if (FoundDirect) {
1240 Found = true;
1241 continue;
1242 }
1243
1244 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1245 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1246 if (Visited.insert(Nom).second)
1247 Queue.push_back(Nom);
1248 }
1249 }
1250
1251 if (Found) {
1252 if (FoundTag && FoundNonTag)
1253 R.setAmbiguousQualifiedTagHiding();
1254 else
1255 R.resolveKind();
1256 }
1257
1258 return Found;
1259}
1260
Douglas Gregor39982192010-08-15 06:18:01 +00001261/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001263 CXXBasePath &Path,
1264 void *Name) {
1265 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266
Douglas Gregor39982192010-08-15 06:18:01 +00001267 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1268 Path.Decls = BaseRecord->lookup(N);
1269 return Path.Decls.first != Path.Decls.second;
1270}
1271
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001272/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001273/// static members, nested types, and enumerators.
1274template<typename InputIterator>
1275static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1276 Decl *D = (*First)->getUnderlyingDecl();
1277 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1278 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001279
Douglas Gregorc0d24902010-10-22 22:08:47 +00001280 if (isa<CXXMethodDecl>(D)) {
1281 // Determine whether all of the methods are static.
1282 bool AllMethodsAreStatic = true;
1283 for(; First != Last; ++First) {
1284 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001285
Douglas Gregorc0d24902010-10-22 22:08:47 +00001286 if (!isa<CXXMethodDecl>(D)) {
1287 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1288 break;
1289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001290
Douglas Gregorc0d24902010-10-22 22:08:47 +00001291 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1292 AllMethodsAreStatic = false;
1293 break;
1294 }
1295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001296
Douglas Gregorc0d24902010-10-22 22:08:47 +00001297 if (AllMethodsAreStatic)
1298 return true;
1299 }
1300
1301 return false;
1302}
1303
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001304/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001305///
1306/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1307/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001308/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001309///
1310/// Different lookup criteria can find different names. For example, a
1311/// particular scope can have both a struct and a function of the same
1312/// name, and each can be found by certain lookup criteria. For more
1313/// information about lookup criteria, see the documentation for the
1314/// class LookupCriteria.
1315///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001316/// \param R captures both the lookup criteria and any lookup results found.
1317///
1318/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001319/// search. If the lookup criteria permits, name lookup may also search
1320/// in the parent contexts or (for C++ classes) base classes.
1321///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001322/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001323/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001324///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001325/// \returns true if lookup succeeded, false if it failed.
1326bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1327 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001328 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001329
John McCall27b18f82009-11-17 02:14:36 +00001330 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001331 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001332
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001333 // Make sure that the declaration context is complete.
1334 assert((!isa<TagDecl>(LookupCtx) ||
1335 LookupCtx->isDependentContext() ||
1336 cast<TagDecl>(LookupCtx)->isDefinition() ||
1337 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1338 ->isBeingDefined()) &&
1339 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001340
Douglas Gregor34074322009-01-14 22:20:51 +00001341 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001342 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001343 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001344 if (isa<CXXRecordDecl>(LookupCtx))
1345 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001346 return true;
1347 }
Douglas Gregor34074322009-01-14 22:20:51 +00001348
John McCall6538c932009-10-10 05:48:19 +00001349 // Don't descend into implied contexts for redeclarations.
1350 // C++98 [namespace.qual]p6:
1351 // In a declaration for a namespace member in which the
1352 // declarator-id is a qualified-id, given that the qualified-id
1353 // for the namespace member has the form
1354 // nested-name-specifier unqualified-id
1355 // the unqualified-id shall name a member of the namespace
1356 // designated by the nested-name-specifier.
1357 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001358 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001359 return false;
1360
John McCall27b18f82009-11-17 02:14:36 +00001361 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001362 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001363 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001364
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001365 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001366 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001367 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001368 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001369 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001370
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001371 // If we're performing qualified name lookup into a dependent class,
1372 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001373 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001374 // template instantiation time (at which point all bases will be available)
1375 // or we have to fail.
1376 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1377 LookupRec->hasAnyDependentBases()) {
1378 R.setNotFoundInCurrentInstantiation();
1379 return false;
1380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001382 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001383 CXXBasePaths Paths;
1384 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001385
1386 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001387 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001388 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001389 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001390 case LookupOrdinaryName:
1391 case LookupMemberName:
1392 case LookupRedeclarationWithLinkage:
1393 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1394 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395
Douglas Gregor36d1b142009-10-06 17:59:45 +00001396 case LookupTagName:
1397 BaseCallback = &CXXRecordDecl::FindTagMember;
1398 break;
John McCall84d87672009-12-10 09:41:52 +00001399
Douglas Gregor39982192010-08-15 06:18:01 +00001400 case LookupAnyName:
1401 BaseCallback = &LookupAnyMember;
1402 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001403
John McCall84d87672009-12-10 09:41:52 +00001404 case LookupUsingDeclName:
1405 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001406
Douglas Gregor36d1b142009-10-06 17:59:45 +00001407 case LookupOperatorName:
1408 case LookupNamespaceName:
1409 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001410 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001411 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001412 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413
Douglas Gregor36d1b142009-10-06 17:59:45 +00001414 case LookupNestedNameSpecifierName:
1415 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1416 break;
1417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001418
John McCall27b18f82009-11-17 02:14:36 +00001419 if (!LookupRec->lookupInBases(BaseCallback,
1420 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001421 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001422
John McCall553c0792010-01-23 00:46:32 +00001423 R.setNamingClass(LookupRec);
1424
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001425 // C++ [class.member.lookup]p2:
1426 // [...] If the resulting set of declarations are not all from
1427 // sub-objects of the same type, or the set has a nonstatic member
1428 // and includes members from distinct sub-objects, there is an
1429 // ambiguity and the program is ill-formed. Otherwise that set is
1430 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001431 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001432 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001433 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001434
Douglas Gregor36d1b142009-10-06 17:59:45 +00001435 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001436 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001437 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001438
John McCall401982f2010-01-20 21:53:11 +00001439 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1440 // across all paths.
1441 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001442
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001443 // Determine whether we're looking at a distinct sub-object or not.
1444 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001445 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001446 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1447 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001448 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001449 }
1450
Douglas Gregorc0d24902010-10-22 22:08:47 +00001451 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001452 != Context.getCanonicalType(PathElement.Base->getType())) {
1453 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001454 // different types. If the declaration sets aren't the same, this
1455 // this lookup is ambiguous.
1456 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1457 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1458 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1459 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001460
Douglas Gregorc0d24902010-10-22 22:08:47 +00001461 while (FirstD != FirstPath->Decls.second &&
1462 CurrentD != Path->Decls.second) {
1463 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1464 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1465 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466
Douglas Gregorc0d24902010-10-22 22:08:47 +00001467 ++FirstD;
1468 ++CurrentD;
1469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470
Douglas Gregorc0d24902010-10-22 22:08:47 +00001471 if (FirstD == FirstPath->Decls.second &&
1472 CurrentD == Path->Decls.second)
1473 continue;
1474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001475
John McCall9f3059a2009-10-09 21:13:30 +00001476 R.setAmbiguousBaseSubobjectTypes(Paths);
1477 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001478 }
1479
Douglas Gregorc0d24902010-10-22 22:08:47 +00001480 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001481 // We have a different subobject of the same type.
1482
1483 // C++ [class.member.lookup]p5:
1484 // A static member, a nested type or an enumerator defined in
1485 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001486 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001487 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001488 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001489
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001490 // We have found a nonstatic member name in multiple, distinct
1491 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001492 R.setAmbiguousBaseSubobjects(Paths);
1493 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001494 }
1495 }
1496
1497 // Lookup in a base class succeeded; return these results.
1498
John McCall9f3059a2009-10-09 21:13:30 +00001499 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001500 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1501 NamedDecl *D = *I;
1502 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1503 D->getAccess());
1504 R.addDecl(D, AS);
1505 }
John McCall9f3059a2009-10-09 21:13:30 +00001506 R.resolveKind();
1507 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001508}
1509
1510/// @brief Performs name lookup for a name that was parsed in the
1511/// source code, and may contain a C++ scope specifier.
1512///
1513/// This routine is a convenience routine meant to be called from
1514/// contexts that receive a name and an optional C++ scope specifier
1515/// (e.g., "N::M::x"). It will then perform either qualified or
1516/// unqualified name lookup (with LookupQualifiedName or LookupName,
1517/// respectively) on the given name and return those results.
1518///
1519/// @param S The scope from which unqualified name lookup will
1520/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001521///
Douglas Gregore861bac2009-08-25 22:51:20 +00001522/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001523///
Douglas Gregore861bac2009-08-25 22:51:20 +00001524/// @param EnteringContext Indicates whether we are going to enter the
1525/// context of the scope-specifier SS (if present).
1526///
John McCall9f3059a2009-10-09 21:13:30 +00001527/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001528bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001529 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001530 if (SS && SS->isInvalid()) {
1531 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001532 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001533 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
Douglas Gregore861bac2009-08-25 22:51:20 +00001536 if (SS && SS->isSet()) {
1537 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001538 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001539 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001540 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001541 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001542
John McCall27b18f82009-11-17 02:14:36 +00001543 R.setContextRange(SS->getRange());
1544
1545 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001546 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001547
Douglas Gregore861bac2009-08-25 22:51:20 +00001548 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001549 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001550 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001551 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001552 }
1553
Mike Stump11289f42009-09-09 15:08:12 +00001554 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001555 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001556}
1557
Douglas Gregor889ceb72009-02-03 19:21:40 +00001558
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001559/// @brief Produce a diagnostic describing the ambiguity that resulted
1560/// from name lookup.
1561///
1562/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001563///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001564/// @param Name The name of the entity that name lookup was
1565/// searching for.
1566///
1567/// @param NameLoc The location of the name within the source code.
1568///
1569/// @param LookupRange A source range that provides more
1570/// source-location information concerning the lookup itself. For
1571/// example, this range might highlight a nested-name-specifier that
1572/// precedes the name.
1573///
1574/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001575bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001576 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1577
John McCall27b18f82009-11-17 02:14:36 +00001578 DeclarationName Name = Result.getLookupName();
1579 SourceLocation NameLoc = Result.getNameLoc();
1580 SourceRange LookupRange = Result.getContextRange();
1581
John McCall6538c932009-10-10 05:48:19 +00001582 switch (Result.getAmbiguityKind()) {
1583 case LookupResult::AmbiguousBaseSubobjects: {
1584 CXXBasePaths *Paths = Result.getBasePaths();
1585 QualType SubobjectType = Paths->front().back().Base->getType();
1586 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1587 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1588 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001589
John McCall6538c932009-10-10 05:48:19 +00001590 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1591 while (isa<CXXMethodDecl>(*Found) &&
1592 cast<CXXMethodDecl>(*Found)->isStatic())
1593 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001594
John McCall6538c932009-10-10 05:48:19 +00001595 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001596
John McCall6538c932009-10-10 05:48:19 +00001597 return true;
1598 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001599
John McCall6538c932009-10-10 05:48:19 +00001600 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001601 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1602 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001603
John McCall6538c932009-10-10 05:48:19 +00001604 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001605 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001606 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1607 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001608 Path != PathEnd; ++Path) {
1609 Decl *D = *Path->Decls.first;
1610 if (DeclsPrinted.insert(D).second)
1611 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1612 }
1613
Douglas Gregor1c846b02009-01-16 00:38:09 +00001614 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001615 }
1616
John McCall6538c932009-10-10 05:48:19 +00001617 case LookupResult::AmbiguousTagHiding: {
1618 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001619
John McCall6538c932009-10-10 05:48:19 +00001620 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1621
1622 LookupResult::iterator DI, DE = Result.end();
1623 for (DI = Result.begin(); DI != DE; ++DI)
1624 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1625 TagDecls.insert(TD);
1626 Diag(TD->getLocation(), diag::note_hidden_tag);
1627 }
1628
1629 for (DI = Result.begin(); DI != DE; ++DI)
1630 if (!isa<TagDecl>(*DI))
1631 Diag((*DI)->getLocation(), diag::note_hiding_object);
1632
1633 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001634 LookupResult::Filter F = Result.makeFilter();
1635 while (F.hasNext()) {
1636 if (TagDecls.count(F.next()))
1637 F.erase();
1638 }
1639 F.done();
John McCall6538c932009-10-10 05:48:19 +00001640
1641 return true;
1642 }
1643
1644 case LookupResult::AmbiguousReference: {
1645 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001646
John McCall6538c932009-10-10 05:48:19 +00001647 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1648 for (; DI != DE; ++DI)
1649 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001650
John McCall6538c932009-10-10 05:48:19 +00001651 return true;
1652 }
1653 }
1654
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001655 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001656 return true;
1657}
Douglas Gregore254f902009-02-04 00:32:51 +00001658
John McCallf24d7bb2010-05-28 18:45:08 +00001659namespace {
1660 struct AssociatedLookup {
1661 AssociatedLookup(Sema &S,
1662 Sema::AssociatedNamespaceSet &Namespaces,
1663 Sema::AssociatedClassSet &Classes)
1664 : S(S), Namespaces(Namespaces), Classes(Classes) {
1665 }
1666
1667 Sema &S;
1668 Sema::AssociatedNamespaceSet &Namespaces;
1669 Sema::AssociatedClassSet &Classes;
1670 };
1671}
1672
Mike Stump11289f42009-09-09 15:08:12 +00001673static void
John McCallf24d7bb2010-05-28 18:45:08 +00001674addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001675
Douglas Gregor8b895222010-04-30 07:08:38 +00001676static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1677 DeclContext *Ctx) {
1678 // Add the associated namespace for this class.
1679
1680 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1681 // be a locally scoped record.
1682
Sebastian Redlbd595762010-08-31 20:53:31 +00001683 // We skip out of inline namespaces. The innermost non-inline namespace
1684 // contains all names of all its nested inline namespaces anyway, so we can
1685 // replace the entire inline namespace tree with its root.
1686 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1687 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001688 Ctx = Ctx->getParent();
1689
John McCallc7e8e792009-08-07 22:18:02 +00001690 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001691 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001692}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001693
Mike Stump11289f42009-09-09 15:08:12 +00001694// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001695// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001696static void
John McCallf24d7bb2010-05-28 18:45:08 +00001697addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1698 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001699 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001700 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001701 switch (Arg.getKind()) {
1702 case TemplateArgument::Null:
1703 break;
Mike Stump11289f42009-09-09 15:08:12 +00001704
Douglas Gregor197e5f72009-07-08 07:51:57 +00001705 case TemplateArgument::Type:
1706 // [...] the namespaces and classes associated with the types of the
1707 // template arguments provided for template type parameters (excluding
1708 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001709 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001710 break;
Mike Stump11289f42009-09-09 15:08:12 +00001711
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001712 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001713 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001714 // [...] the namespaces in which any template template arguments are
1715 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001716 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001717 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001718 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001719 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001720 DeclContext *Ctx = ClassTemplate->getDeclContext();
1721 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001722 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001723 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001724 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001725 }
1726 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001729 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001730 case TemplateArgument::Integral:
1731 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001732 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001733 // associated namespaces. ]
1734 break;
Mike Stump11289f42009-09-09 15:08:12 +00001735
Douglas Gregor197e5f72009-07-08 07:51:57 +00001736 case TemplateArgument::Pack:
1737 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1738 PEnd = Arg.pack_end();
1739 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001740 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001741 break;
1742 }
1743}
1744
Douglas Gregore254f902009-02-04 00:32:51 +00001745// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001746// argument-dependent lookup with an argument of class type
1747// (C++ [basic.lookup.koenig]p2).
1748static void
John McCallf24d7bb2010-05-28 18:45:08 +00001749addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1750 CXXRecordDecl *Class) {
1751
1752 // Just silently ignore anything whose name is __va_list_tag.
1753 if (Class->getDeclName() == Result.S.VAListTagName)
1754 return;
1755
Douglas Gregore254f902009-02-04 00:32:51 +00001756 // C++ [basic.lookup.koenig]p2:
1757 // [...]
1758 // -- If T is a class type (including unions), its associated
1759 // classes are: the class itself; the class of which it is a
1760 // member, if any; and its direct and indirect base
1761 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001762 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001763
1764 // Add the class of which it is a member, if any.
1765 DeclContext *Ctx = Class->getDeclContext();
1766 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001767 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001768 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001769 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001770
Douglas Gregore254f902009-02-04 00:32:51 +00001771 // Add the class itself. If we've already seen this class, we don't
1772 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001773 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001774 return;
1775
Mike Stump11289f42009-09-09 15:08:12 +00001776 // -- If T is a template-id, its associated namespaces and classes are
1777 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001778 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001779 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001780 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001781 // namespaces in which any template template arguments are defined; and
1782 // the classes in which any member templates used as template template
1783 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001784 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001785 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001786 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1787 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1788 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001789 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001790 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001791 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001792
Douglas Gregor197e5f72009-07-08 07:51:57 +00001793 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1794 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001795 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001796 }
Mike Stump11289f42009-09-09 15:08:12 +00001797
John McCall67da35c2010-02-04 22:26:26 +00001798 // Only recurse into base classes for complete types.
1799 if (!Class->hasDefinition()) {
1800 // FIXME: we might need to instantiate templates here
1801 return;
1802 }
1803
Douglas Gregore254f902009-02-04 00:32:51 +00001804 // Add direct and indirect base classes along with their associated
1805 // namespaces.
1806 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1807 Bases.push_back(Class);
1808 while (!Bases.empty()) {
1809 // Pop this class off the stack.
1810 Class = Bases.back();
1811 Bases.pop_back();
1812
1813 // Visit the base classes.
1814 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1815 BaseEnd = Class->bases_end();
1816 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001817 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001818 // In dependent contexts, we do ADL twice, and the first time around,
1819 // the base type might be a dependent TemplateSpecializationType, or a
1820 // TemplateTypeParmType. If that happens, simply ignore it.
1821 // FIXME: If we want to support export, we probably need to add the
1822 // namespace of the template in a TemplateSpecializationType, or even
1823 // the classes and namespaces of known non-dependent arguments.
1824 if (!BaseType)
1825 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001826 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001827 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001828 // Find the associated namespace for this base class.
1829 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001830 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001831
1832 // Make sure we visit the bases of this base class.
1833 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1834 Bases.push_back(BaseDecl);
1835 }
1836 }
1837 }
1838}
1839
1840// \brief Add the associated classes and namespaces for
1841// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001842// (C++ [basic.lookup.koenig]p2).
1843static void
John McCallf24d7bb2010-05-28 18:45:08 +00001844addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001845 // C++ [basic.lookup.koenig]p2:
1846 //
1847 // For each argument type T in the function call, there is a set
1848 // of zero or more associated namespaces and a set of zero or more
1849 // associated classes to be considered. The sets of namespaces and
1850 // classes is determined entirely by the types of the function
1851 // arguments (and the namespace of any template template
1852 // argument). Typedef names and using-declarations used to specify
1853 // the types do not contribute to this set. The sets of namespaces
1854 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001855
John McCall0af3d3b2010-05-28 06:08:54 +00001856 llvm::SmallVector<const Type *, 16> Queue;
1857 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1858
Douglas Gregore254f902009-02-04 00:32:51 +00001859 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001860 switch (T->getTypeClass()) {
1861
1862#define TYPE(Class, Base)
1863#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1864#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1865#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1866#define ABSTRACT_TYPE(Class, Base)
1867#include "clang/AST/TypeNodes.def"
1868 // T is canonical. We can also ignore dependent types because
1869 // we don't need to do ADL at the definition point, but if we
1870 // wanted to implement template export (or if we find some other
1871 // use for associated classes and namespaces...) this would be
1872 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001873 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001874
John McCall0af3d3b2010-05-28 06:08:54 +00001875 // -- If T is a pointer to U or an array of U, its associated
1876 // namespaces and classes are those associated with U.
1877 case Type::Pointer:
1878 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1879 continue;
1880 case Type::ConstantArray:
1881 case Type::IncompleteArray:
1882 case Type::VariableArray:
1883 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1884 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001885
John McCall0af3d3b2010-05-28 06:08:54 +00001886 // -- If T is a fundamental type, its associated sets of
1887 // namespaces and classes are both empty.
1888 case Type::Builtin:
1889 break;
1890
1891 // -- If T is a class type (including unions), its associated
1892 // classes are: the class itself; the class of which it is a
1893 // member, if any; and its direct and indirect base
1894 // classes. Its associated namespaces are the namespaces in
1895 // which its associated classes are defined.
1896 case Type::Record: {
1897 CXXRecordDecl *Class
1898 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001899 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001900 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001901 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001902
John McCall0af3d3b2010-05-28 06:08:54 +00001903 // -- If T is an enumeration type, its associated namespace is
1904 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001905 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001906 // it has no associated class.
1907 case Type::Enum: {
1908 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001909
John McCall0af3d3b2010-05-28 06:08:54 +00001910 DeclContext *Ctx = Enum->getDeclContext();
1911 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001912 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001913
John McCall0af3d3b2010-05-28 06:08:54 +00001914 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001915 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001916
John McCall0af3d3b2010-05-28 06:08:54 +00001917 break;
1918 }
1919
1920 // -- If T is a function type, its associated namespaces and
1921 // classes are those associated with the function parameter
1922 // types and those associated with the return type.
1923 case Type::FunctionProto: {
1924 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1925 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1926 ArgEnd = Proto->arg_type_end();
1927 Arg != ArgEnd; ++Arg)
1928 Queue.push_back(Arg->getTypePtr());
1929 // fallthrough
1930 }
1931 case Type::FunctionNoProto: {
1932 const FunctionType *FnType = cast<FunctionType>(T);
1933 T = FnType->getResultType().getTypePtr();
1934 continue;
1935 }
1936
1937 // -- If T is a pointer to a member function of a class X, its
1938 // associated namespaces and classes are those associated
1939 // with the function parameter types and return type,
1940 // together with those associated with X.
1941 //
1942 // -- If T is a pointer to a data member of class X, its
1943 // associated namespaces and classes are those associated
1944 // with the member type together with those associated with
1945 // X.
1946 case Type::MemberPointer: {
1947 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1948
1949 // Queue up the class type into which this points.
1950 Queue.push_back(MemberPtr->getClass());
1951
1952 // And directly continue with the pointee type.
1953 T = MemberPtr->getPointeeType().getTypePtr();
1954 continue;
1955 }
1956
1957 // As an extension, treat this like a normal pointer.
1958 case Type::BlockPointer:
1959 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1960 continue;
1961
1962 // References aren't covered by the standard, but that's such an
1963 // obvious defect that we cover them anyway.
1964 case Type::LValueReference:
1965 case Type::RValueReference:
1966 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1967 continue;
1968
1969 // These are fundamental types.
1970 case Type::Vector:
1971 case Type::ExtVector:
1972 case Type::Complex:
1973 break;
1974
Douglas Gregor8e936662011-04-12 01:02:45 +00001975 // If T is an Objective-C object or interface type, or a pointer to an
1976 // object or interface type, the associated namespace is the global
1977 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00001978 case Type::ObjCObject:
1979 case Type::ObjCInterface:
1980 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00001981 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00001982 break;
1983 }
1984
1985 if (Queue.empty()) break;
1986 T = Queue.back();
1987 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001988 }
Douglas Gregore254f902009-02-04 00:32:51 +00001989}
1990
1991/// \brief Find the associated classes and namespaces for
1992/// argument-dependent lookup for a call with the given set of
1993/// arguments.
1994///
1995/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001996/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001997/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001998void
Douglas Gregore254f902009-02-04 00:32:51 +00001999Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2000 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002001 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002002 AssociatedNamespaces.clear();
2003 AssociatedClasses.clear();
2004
John McCallf24d7bb2010-05-28 18:45:08 +00002005 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2006
Douglas Gregore254f902009-02-04 00:32:51 +00002007 // C++ [basic.lookup.koenig]p2:
2008 // For each argument type T in the function call, there is a set
2009 // of zero or more associated namespaces and a set of zero or more
2010 // associated classes to be considered. The sets of namespaces and
2011 // classes is determined entirely by the types of the function
2012 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002013 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00002014 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2015 Expr *Arg = Args[ArgIdx];
2016
2017 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002018 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002019 continue;
2020 }
2021
2022 // [...] In addition, if the argument is the name or address of a
2023 // set of overloaded functions and/or function templates, its
2024 // associated classes and namespaces are the union of those
2025 // associated with each of the members of the set: the namespace
2026 // in which the function or function template is defined and the
2027 // classes and namespaces associated with its (non-dependent)
2028 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002029 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002030 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002031 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002032 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002033
John McCallf24d7bb2010-05-28 18:45:08 +00002034 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2035 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002036
John McCallf24d7bb2010-05-28 18:45:08 +00002037 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2038 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002039 // Look through any using declarations to find the underlying function.
2040 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002041
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002042 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2043 if (!FDecl)
2044 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002045
2046 // Add the classes and namespaces associated with the parameter
2047 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002048 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002049 }
2050 }
2051}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002052
2053/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2054/// an acceptable non-member overloaded operator for a call whose
2055/// arguments have types T1 (and, if non-empty, T2). This routine
2056/// implements the check in C++ [over.match.oper]p3b2 concerning
2057/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002058static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002059IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2060 QualType T1, QualType T2,
2061 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002062 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2063 return true;
2064
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002065 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2066 return true;
2067
John McCall9dd450b2009-09-21 23:43:11 +00002068 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002069 if (Proto->getNumArgs() < 1)
2070 return false;
2071
2072 if (T1->isEnumeralType()) {
2073 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002074 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002075 return true;
2076 }
2077
2078 if (Proto->getNumArgs() < 2)
2079 return false;
2080
2081 if (!T2.isNull() && T2->isEnumeralType()) {
2082 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002083 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002084 return true;
2085 }
2086
2087 return false;
2088}
2089
John McCall5cebab12009-11-18 07:57:50 +00002090NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002091 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002092 LookupNameKind NameKind,
2093 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002094 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002095 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002096 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002097}
2098
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002099/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002100ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002101 SourceLocation IdLoc) {
2102 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2103 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002104 return cast_or_null<ObjCProtocolDecl>(D);
2105}
2106
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002107void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002108 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002109 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002110 // C++ [over.match.oper]p3:
2111 // -- The set of non-member candidates is the result of the
2112 // unqualified lookup of operator@ in the context of the
2113 // expression according to the usual rules for name lookup in
2114 // unqualified function calls (3.4.2) except that all member
2115 // functions are ignored. However, if no operand has a class
2116 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002117 // that have a first parameter of type T1 or "reference to
2118 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002119 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002120 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002121 // when T2 is an enumeration type, are candidate functions.
2122 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002123 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2124 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002125
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002126 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2127
John McCall9f3059a2009-10-09 21:13:30 +00002128 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002129 return;
2130
2131 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2132 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002133 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2134 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002135 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002136 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002137 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002138 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002139 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002140 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002141 // later?
2142 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002143 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002144 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002145 }
2146}
2147
Alexis Hunt1da39282011-06-24 02:11:39 +00002148Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002149 CXXSpecialMember SM,
2150 bool ConstArg,
2151 bool VolatileArg,
2152 bool RValueThis,
2153 bool ConstThis,
2154 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002155 RD = RD->getDefinition();
2156 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002157 "doing special member lookup into record that isn't fully complete");
2158 if (RValueThis || ConstThis || VolatileThis)
2159 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2160 "constructors and destructors always have unqualified lvalue this");
2161 if (ConstArg || VolatileArg)
2162 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2163 "parameter-less special members can't have qualified arguments");
2164
2165 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002166 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002167 ID.AddInteger(SM);
2168 ID.AddInteger(ConstArg);
2169 ID.AddInteger(VolatileArg);
2170 ID.AddInteger(RValueThis);
2171 ID.AddInteger(ConstThis);
2172 ID.AddInteger(VolatileThis);
2173
2174 void *InsertPoint;
2175 SpecialMemberOverloadResult *Result =
2176 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2177
2178 // This was already cached
2179 if (Result)
2180 return Result;
2181
Alexis Huntba8e18d2011-06-07 00:11:58 +00002182 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2183 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002184 SpecialMemberCache.InsertNode(Result, InsertPoint);
2185
2186 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002187 if (!RD->hasDeclaredDestructor())
2188 DeclareImplicitDestructor(RD);
2189 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002190 assert(DD && "record without a destructor");
2191 Result->setMethod(DD);
2192 Result->setSuccess(DD->isDeleted());
2193 Result->setConstParamMatch(false);
2194 return Result;
2195 }
2196
Alexis Hunteef8ee02011-06-10 03:50:41 +00002197 // Prepare for overload resolution. Here we construct a synthetic argument
2198 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002199 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002200 DeclarationName Name;
2201 Expr *Arg = 0;
2202 unsigned NumArgs;
2203
2204 if (SM == CXXDefaultConstructor) {
2205 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2206 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002207 if (RD->needsImplicitDefaultConstructor())
2208 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002209 } else {
2210 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2211 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002212 if (!RD->hasDeclaredCopyConstructor())
2213 DeclareImplicitCopyConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002214 // TODO: Move constructors
2215 } else {
2216 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002217 if (!RD->hasDeclaredCopyAssignment())
2218 DeclareImplicitCopyAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002219 // TODO: Move assignment
2220 }
2221
2222 QualType ArgType = CanTy;
2223 if (ConstArg)
2224 ArgType.addConst();
2225 if (VolatileArg)
2226 ArgType.addVolatile();
2227
2228 // This isn't /really/ specified by the standard, but it's implied
2229 // we should be working from an RValue in the case of move to ensure
2230 // that we prefer to bind to rvalue references, and an LValue in the
2231 // case of copy to ensure we don't bind to rvalue references.
2232 // Possibly an XValue is actually correct in the case of move, but
2233 // there is no semantic difference for class types in this restricted
2234 // case.
2235 ExprValueKind VK;
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002236 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002237 VK = VK_LValue;
2238 else
2239 VK = VK_RValue;
2240
2241 NumArgs = 1;
2242 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2243 }
2244
2245 // Create the object argument
2246 QualType ThisTy = CanTy;
2247 if (ConstThis)
2248 ThisTy.addConst();
2249 if (VolatileThis)
2250 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002251 Expr::Classification Classification =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002252 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2253 RValueThis ? VK_RValue : VK_LValue))->
2254 Classify(Context);
2255
2256 // Now we perform lookup on the name we computed earlier and do overload
2257 // resolution. Lookup is only performed directly into the class since there
2258 // will always be a (possibly implicit) declaration to shadow any others.
2259 OverloadCandidateSet OCS((SourceLocation()));
2260 DeclContext::lookup_iterator I, E;
2261 Result->setConstParamMatch(false);
2262
Alexis Hunt1da39282011-06-24 02:11:39 +00002263 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002264 assert((I != E) &&
2265 "lookup for a constructor or assignment operator was empty");
2266 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002267 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002268
Alexis Hunt1da39282011-06-24 02:11:39 +00002269 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002270 continue;
2271
Alexis Hunt1da39282011-06-24 02:11:39 +00002272 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2273 // FIXME: [namespace.udecl]p15 says that we should only consider a
2274 // using declaration here if it does not match a declaration in the
2275 // derived class. We do not implement this correctly in other cases
2276 // either.
2277 Cand = U->getTargetDecl();
2278
2279 if (Cand->isInvalidDecl())
2280 continue;
2281 }
2282
2283 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002284 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002285 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Alexis Hunt080709f2011-06-23 00:26:20 +00002286 Classification, &Arg, NumArgs, OCS, true);
2287 else
2288 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2289 NumArgs, OCS, true);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002290
2291 // Here we're looking for a const parameter to speed up creation of
2292 // implicit copy methods.
2293 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2294 (SM == CXXCopyConstructor &&
2295 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2296 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Alexis Hunt491ec602011-06-21 23:42:56 +00002297 if (!ArgType->isReferenceType() ||
2298 ArgType->getPointeeType().isConstQualified())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002299 Result->setConstParamMatch(true);
2300 }
Alexis Hunt2949f022011-06-22 02:58:46 +00002301 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002302 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002303 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2304 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Alexis Hunt1da39282011-06-24 02:11:39 +00002305 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Alexis Hunt080709f2011-06-23 00:26:20 +00002306 OCS, true);
2307 else
2308 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2309 0, &Arg, NumArgs, OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002310 } else {
2311 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002312 }
2313 }
2314
2315 OverloadCandidateSet::iterator Best;
2316 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2317 case OR_Success:
2318 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2319 Result->setSuccess(true);
2320 break;
2321
2322 case OR_Deleted:
2323 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2324 Result->setSuccess(false);
2325 break;
2326
2327 case OR_Ambiguous:
2328 case OR_No_Viable_Function:
2329 Result->setMethod(0);
2330 Result->setSuccess(false);
2331 break;
2332 }
2333
2334 return Result;
2335}
2336
2337/// \brief Look up the default constructor for the given class.
2338CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002339 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002340 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2341 false, false);
2342
2343 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002344}
2345
Alexis Hunt491ec602011-06-21 23:42:56 +00002346/// \brief Look up the copying constructor for the given class.
2347CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2348 unsigned Quals,
2349 bool *ConstParamMatch) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002350 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2351 "non-const, non-volatile qualifiers for copy ctor arg");
2352 SpecialMemberOverloadResult *Result =
2353 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2354 Quals & Qualifiers::Volatile, false, false, false);
2355
2356 if (ConstParamMatch)
2357 *ConstParamMatch = Result->hasConstParamMatch();
2358
2359 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2360}
2361
Douglas Gregor52b72822010-07-02 23:12:18 +00002362/// \brief Look up the constructors for the given class.
2363DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002364 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002365 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002366 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002367 DeclareImplicitDefaultConstructor(Class);
2368 if (!Class->hasDeclaredCopyConstructor())
2369 DeclareImplicitCopyConstructor(Class);
2370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002371
Douglas Gregor52b72822010-07-02 23:12:18 +00002372 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2373 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2374 return Class->lookup(Name);
2375}
2376
Alexis Hunt491ec602011-06-21 23:42:56 +00002377/// \brief Look up the copying assignment operator for the given class.
2378CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2379 unsigned Quals, bool RValueThis,
2380 unsigned ThisQuals,
2381 bool *ConstParamMatch) {
2382 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2383 "non-const, non-volatile qualifiers for copy assignment arg");
2384 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2385 "non-const, non-volatile qualifiers for copy assignment this");
2386 SpecialMemberOverloadResult *Result =
2387 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2388 Quals & Qualifiers::Volatile, RValueThis,
2389 ThisQuals & Qualifiers::Const,
2390 ThisQuals & Qualifiers::Volatile);
2391
2392 if (ConstParamMatch)
2393 *ConstParamMatch = Result->hasConstParamMatch();
2394
2395 return Result->getMethod();
2396}
2397
Douglas Gregore71edda2010-07-01 22:47:18 +00002398/// \brief Look for the destructor of the given class.
2399///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002400/// During semantic analysis, this routine should be used in lieu of
2401/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002402///
2403/// \returns The destructor for this class.
2404CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002405 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2406 false, false, false,
2407 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002408}
2409
John McCall8fe68082010-01-26 07:16:45 +00002410void ADLResult::insert(NamedDecl *New) {
2411 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2412
2413 // If we haven't yet seen a decl for this key, or the last decl
2414 // was exactly this one, we're done.
2415 if (Old == 0 || Old == New) {
2416 Old = New;
2417 return;
2418 }
2419
2420 // Otherwise, decide which is a more recent redeclaration.
2421 FunctionDecl *OldFD, *NewFD;
2422 if (isa<FunctionTemplateDecl>(New)) {
2423 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2424 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2425 } else {
2426 OldFD = cast<FunctionDecl>(Old);
2427 NewFD = cast<FunctionDecl>(New);
2428 }
2429
2430 FunctionDecl *Cursor = NewFD;
2431 while (true) {
2432 Cursor = Cursor->getPreviousDeclaration();
2433
2434 // If we got to the end without finding OldFD, OldFD is the newer
2435 // declaration; leave things as they are.
2436 if (!Cursor) return;
2437
2438 // If we do find OldFD, then NewFD is newer.
2439 if (Cursor == OldFD) break;
2440
2441 // Otherwise, keep looking.
2442 }
2443
2444 Old = New;
2445}
2446
Sebastian Redlc057f422009-10-23 19:23:15 +00002447void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002448 Expr **Args, unsigned NumArgs,
Richard Smith02e85f32011-04-14 22:09:26 +00002449 ADLResult &Result,
2450 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002451 // Find all of the associated namespaces and classes based on the
2452 // arguments we have.
2453 AssociatedNamespaceSet AssociatedNamespaces;
2454 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002455 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002456 AssociatedNamespaces,
2457 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002458 if (StdNamespaceIsAssociated && StdNamespace)
2459 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002460
Sebastian Redlc057f422009-10-23 19:23:15 +00002461 QualType T1, T2;
2462 if (Operator) {
2463 T1 = Args[0]->getType();
2464 if (NumArgs >= 2)
2465 T2 = Args[1]->getType();
2466 }
2467
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002468 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002469 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2470 // and let Y be the lookup set produced by argument dependent
2471 // lookup (defined as follows). If X contains [...] then Y is
2472 // empty. Otherwise Y is the set of declarations found in the
2473 // namespaces associated with the argument types as described
2474 // below. The set of declarations found by the lookup of the name
2475 // is the union of X and Y.
2476 //
2477 // Here, we compute Y and add its members to the overloaded
2478 // candidate set.
2479 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002480 NSEnd = AssociatedNamespaces.end();
2481 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002482 // When considering an associated namespace, the lookup is the
2483 // same as the lookup performed when the associated namespace is
2484 // used as a qualifier (3.4.3.2) except that:
2485 //
2486 // -- Any using-directives in the associated namespace are
2487 // ignored.
2488 //
John McCallc7e8e792009-08-07 22:18:02 +00002489 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002490 // associated classes are visible within their respective
2491 // namespaces even if they are not visible during an ordinary
2492 // lookup (11.4).
2493 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002494 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002495 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002496 // If the only declaration here is an ordinary friend, consider
2497 // it only if it was declared in an associated classes.
2498 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002499 DeclContext *LexDC = D->getLexicalDeclContext();
2500 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2501 continue;
2502 }
Mike Stump11289f42009-09-09 15:08:12 +00002503
John McCall91f61fc2010-01-26 06:04:06 +00002504 if (isa<UsingShadowDecl>(D))
2505 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002506
John McCall91f61fc2010-01-26 06:04:06 +00002507 if (isa<FunctionDecl>(D)) {
2508 if (Operator &&
2509 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2510 T1, T2, Context))
2511 continue;
John McCall8fe68082010-01-26 07:16:45 +00002512 } else if (!isa<FunctionTemplateDecl>(D))
2513 continue;
2514
2515 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002516 }
2517 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002518}
Douglas Gregor2d435302009-12-30 17:04:44 +00002519
2520//----------------------------------------------------------------------------
2521// Search for all visible declarations.
2522//----------------------------------------------------------------------------
2523VisibleDeclConsumer::~VisibleDeclConsumer() { }
2524
2525namespace {
2526
2527class ShadowContextRAII;
2528
2529class VisibleDeclsRecord {
2530public:
2531 /// \brief An entry in the shadow map, which is optimized to store a
2532 /// single declaration (the common case) but can also store a list
2533 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002534 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002535
2536private:
2537 /// \brief A mapping from declaration names to the declarations that have
2538 /// this name within a particular scope.
2539 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2540
2541 /// \brief A list of shadow maps, which is used to model name hiding.
2542 std::list<ShadowMap> ShadowMaps;
2543
2544 /// \brief The declaration contexts we have already visited.
2545 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2546
2547 friend class ShadowContextRAII;
2548
2549public:
2550 /// \brief Determine whether we have already visited this context
2551 /// (and, if not, note that we are going to visit that context now).
2552 bool visitedContext(DeclContext *Ctx) {
2553 return !VisitedContexts.insert(Ctx);
2554 }
2555
Douglas Gregor39982192010-08-15 06:18:01 +00002556 bool alreadyVisitedContext(DeclContext *Ctx) {
2557 return VisitedContexts.count(Ctx);
2558 }
2559
Douglas Gregor2d435302009-12-30 17:04:44 +00002560 /// \brief Determine whether the given declaration is hidden in the
2561 /// current scope.
2562 ///
2563 /// \returns the declaration that hides the given declaration, or
2564 /// NULL if no such declaration exists.
2565 NamedDecl *checkHidden(NamedDecl *ND);
2566
2567 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002568 void add(NamedDecl *ND) {
2569 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2570 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002571};
2572
2573/// \brief RAII object that records when we've entered a shadow context.
2574class ShadowContextRAII {
2575 VisibleDeclsRecord &Visible;
2576
2577 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2578
2579public:
2580 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2581 Visible.ShadowMaps.push_back(ShadowMap());
2582 }
2583
2584 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002585 Visible.ShadowMaps.pop_back();
2586 }
2587};
2588
2589} // end anonymous namespace
2590
Douglas Gregor2d435302009-12-30 17:04:44 +00002591NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002592 // Look through using declarations.
2593 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002594
Douglas Gregor2d435302009-12-30 17:04:44 +00002595 unsigned IDNS = ND->getIdentifierNamespace();
2596 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2597 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2598 SM != SMEnd; ++SM) {
2599 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2600 if (Pos == SM->end())
2601 continue;
2602
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002603 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002604 IEnd = Pos->second.end();
2605 I != IEnd; ++I) {
2606 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002607 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002608 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002609 Decl::IDNS_ObjCProtocol)))
2610 continue;
2611
2612 // Protocols are in distinct namespaces from everything else.
2613 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2614 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2615 (*I)->getIdentifierNamespace() != IDNS)
2616 continue;
2617
Douglas Gregor09bbc652010-01-14 15:47:35 +00002618 // Functions and function templates in the same scope overload
2619 // rather than hide. FIXME: Look for hiding based on function
2620 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002621 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002622 ND->isFunctionOrFunctionTemplate() &&
2623 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002624 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002625
Douglas Gregor2d435302009-12-30 17:04:44 +00002626 // We've found a declaration that hides this one.
2627 return *I;
2628 }
2629 }
2630
2631 return 0;
2632}
2633
2634static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2635 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002636 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002637 VisibleDeclConsumer &Consumer,
2638 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002639 if (!Ctx)
2640 return;
2641
Douglas Gregor2d435302009-12-30 17:04:44 +00002642 // Make sure we don't visit the same context twice.
2643 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2644 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002645
Douglas Gregor7454c562010-07-02 20:37:36 +00002646 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2647 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2648
Douglas Gregor2d435302009-12-30 17:04:44 +00002649 // Enumerate all of the results in this context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002650 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor2d435302009-12-30 17:04:44 +00002651 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002652 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002653 DEnd = CurCtx->decls_end();
2654 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002655 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002656 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002657 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002658 Visited.add(ND);
2659 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002660 } else if (ObjCForwardProtocolDecl *ForwardProto
2661 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2662 for (ObjCForwardProtocolDecl::protocol_iterator
2663 P = ForwardProto->protocol_begin(),
2664 PEnd = ForwardProto->protocol_end();
2665 P != PEnd;
2666 ++P) {
2667 if (Result.isAcceptableDecl(*P)) {
2668 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2669 Visited.add(*P);
2670 }
2671 }
Douglas Gregor04246572011-02-16 01:39:26 +00002672 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2673 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2674 I != IEnd; ++I) {
2675 ObjCInterfaceDecl *IFace = I->getInterface();
2676 if (Result.isAcceptableDecl(IFace)) {
2677 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2678 Visited.add(IFace);
2679 }
2680 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002681 }
Douglas Gregor04246572011-02-16 01:39:26 +00002682
Sebastian Redlbd595762010-08-31 20:53:31 +00002683 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002684 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002685 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002686 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002687 Consumer, Visited);
2688 }
2689 }
2690 }
2691
2692 // Traverse using directives for qualified name lookup.
2693 if (QualifiedNameLookup) {
2694 ShadowContextRAII Shadow(Visited);
2695 DeclContext::udir_iterator I, E;
2696 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002697 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002698 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002699 }
2700 }
2701
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002702 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002703 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002704 if (!Record->hasDefinition())
2705 return;
2706
Douglas Gregor2d435302009-12-30 17:04:44 +00002707 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2708 BEnd = Record->bases_end();
2709 B != BEnd; ++B) {
2710 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002711
Douglas Gregor2d435302009-12-30 17:04:44 +00002712 // Don't look into dependent bases, because name lookup can't look
2713 // there anyway.
2714 if (BaseType->isDependentType())
2715 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002716
Douglas Gregor2d435302009-12-30 17:04:44 +00002717 const RecordType *Record = BaseType->getAs<RecordType>();
2718 if (!Record)
2719 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002720
Douglas Gregor2d435302009-12-30 17:04:44 +00002721 // FIXME: It would be nice to be able to determine whether referencing
2722 // a particular member would be ambiguous. For example, given
2723 //
2724 // struct A { int member; };
2725 // struct B { int member; };
2726 // struct C : A, B { };
2727 //
2728 // void f(C *c) { c->### }
2729 //
2730 // accessing 'member' would result in an ambiguity. However, we
2731 // could be smart enough to qualify the member with the base
2732 // class, e.g.,
2733 //
2734 // c->B::member
2735 //
2736 // or
2737 //
2738 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002739
Douglas Gregor2d435302009-12-30 17:04:44 +00002740 // Find results in this base class (and its bases).
2741 ShadowContextRAII Shadow(Visited);
2742 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002743 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002744 }
2745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002747 // Traverse the contexts of Objective-C classes.
2748 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2749 // Traverse categories.
2750 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2751 Category; Category = Category->getNextClassCategory()) {
2752 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002753 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002754 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002755 }
2756
2757 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002758 for (ObjCInterfaceDecl::all_protocol_iterator
2759 I = IFace->all_referenced_protocol_begin(),
2760 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002761 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002762 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002763 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002764 }
2765
2766 // Traverse the superclass.
2767 if (IFace->getSuperClass()) {
2768 ShadowContextRAII Shadow(Visited);
2769 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002770 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002772
Douglas Gregor0b59e802010-04-19 18:02:19 +00002773 // If there is an implementation, traverse it. We do this to find
2774 // synthesized ivars.
2775 if (IFace->getImplementation()) {
2776 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002777 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002778 QualifiedNameLookup, true, Consumer, Visited);
2779 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002780 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2781 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2782 E = Protocol->protocol_end(); I != E; ++I) {
2783 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002785 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002786 }
2787 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2788 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2789 E = Category->protocol_end(); I != E; ++I) {
2790 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002791 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002792 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002794
Douglas Gregor0b59e802010-04-19 18:02:19 +00002795 // If there is an implementation, traverse it.
2796 if (Category->getImplementation()) {
2797 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002798 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002799 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002800 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002801 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002802}
2803
2804static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2805 UnqualUsingDirectiveSet &UDirs,
2806 VisibleDeclConsumer &Consumer,
2807 VisibleDeclsRecord &Visited) {
2808 if (!S)
2809 return;
2810
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002811 if (!S->getEntity() ||
2812 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00002813 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002814 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2815 // Walk through the declarations in this Scope.
2816 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2817 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002818 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002819 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002820 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002821 Visited.add(ND);
2822 }
2823 }
2824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002825
Douglas Gregor66230062010-03-15 14:33:29 +00002826 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002827 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002828 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002829 // Look into this scope's declaration context, along with any of its
2830 // parent lookup contexts (e.g., enclosing classes), up to the point
2831 // where we hit the context stored in the next outer scope.
2832 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002833 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002834
Douglas Gregorea166062010-03-15 15:26:48 +00002835 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002836 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002837 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2838 if (Method->isInstanceMethod()) {
2839 // For instance methods, look for ivars in the method's interface.
2840 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2841 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002842 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002843 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002844 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002845
Douglas Gregor05fcf842010-11-02 20:36:02 +00002846 // Look for properties from which we can synthesize ivars, if
2847 // permitted.
2848 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2849 IFace->getImplementation() &&
2850 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002851 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregor05fcf842010-11-02 20:36:02 +00002852 P = IFace->prop_begin(),
2853 PEnd = IFace->prop_end();
2854 P != PEnd; ++P) {
2855 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2856 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2857 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2858 Visited.add(*P);
2859 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002860 }
2861 }
Douglas Gregor05fcf842010-11-02 20:36:02 +00002862 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002863 }
2864
2865 // We've already performed all of the name lookup that we need
2866 // to for Objective-C methods; the next context will be the
2867 // outer scope.
2868 break;
2869 }
2870
Douglas Gregor2d435302009-12-30 17:04:44 +00002871 if (Ctx->isFunctionOrMethod())
2872 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873
2874 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002875 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002876 }
2877 } else if (!S->getParent()) {
2878 // Look into the translation unit scope. We walk through the translation
2879 // unit's declaration context, because the Scope itself won't have all of
2880 // the declarations if we loaded a precompiled header.
2881 // FIXME: We would like the translation unit's Scope object to point to the
2882 // translation unit, so we don't need this special "if" branch. However,
2883 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002884 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00002885 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002886 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002887 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002888 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002889 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002890 }
2891
Douglas Gregor2d435302009-12-30 17:04:44 +00002892 if (Entity) {
2893 // Lookup visible declarations in any namespaces found by using
2894 // directives.
2895 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2896 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2897 for (; UI != UEnd; ++UI)
2898 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002899 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002900 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002901 }
2902
2903 // Lookup names in the parent scope.
2904 ShadowContextRAII Shadow(Visited);
2905 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2906}
2907
2908void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002909 VisibleDeclConsumer &Consumer,
2910 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002911 // Determine the set of using directives available during
2912 // unqualified name lookup.
2913 Scope *Initial = S;
2914 UnqualUsingDirectiveSet UDirs;
2915 if (getLangOptions().CPlusPlus) {
2916 // Find the first namespace or translation-unit scope.
2917 while (S && !isNamespaceOrTranslationUnitScope(S))
2918 S = S->getParent();
2919
2920 UDirs.visitScopeChain(Initial, S);
2921 }
2922 UDirs.done();
2923
2924 // Look for visible declarations.
2925 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2926 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002927 if (!IncludeGlobalScope)
2928 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002929 ShadowContextRAII Shadow(Visited);
2930 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2931}
2932
2933void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002934 VisibleDeclConsumer &Consumer,
2935 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002936 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2937 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002938 if (!IncludeGlobalScope)
2939 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002940 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002941 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002942 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002943}
2944
Chris Lattner43e7f312011-02-18 02:08:43 +00002945/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002946/// If GnuLabelLoc is a valid source location, then this is a definition
2947/// of an __label__ label name, otherwise it is a normal label definition
2948/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00002949LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002950 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002951 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00002952 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002953
2954 if (GnuLabelLoc.isValid()) {
2955 // Local label definitions always shadow existing labels.
2956 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
2957 Scope *S = CurScope;
2958 PushOnScopeChains(Res, S, true);
2959 return cast<LabelDecl>(Res);
2960 }
2961
2962 // Not a GNU local label.
2963 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
2964 // If we found a label, check to see if it is in the same context as us.
2965 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002966 if (Res && Res->getDeclContext() != CurContext)
2967 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002968 if (Res == 0) {
2969 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002970 Res = LabelDecl::Create(Context, CurContext, Loc, II);
2971 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00002972 assert(S && "Not in a function?");
2973 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002974 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002975 return cast<LabelDecl>(Res);
2976}
2977
2978//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00002979// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002980//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00002981
2982namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002983
2984typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00002985typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002986
2987static const unsigned MaxTypoDistanceResultSets = 5;
2988
Douglas Gregor2d435302009-12-30 17:04:44 +00002989class TypoCorrectionConsumer : public VisibleDeclConsumer {
2990 /// \brief The name written that is a typo in the source.
2991 llvm::StringRef Typo;
2992
2993 /// \brief The results found that have the smallest edit distance
2994 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002995 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002996 /// The pointer value being set to the current DeclContext indicates
2997 /// whether there is a keyword with this name.
2998 TypoEditDistanceMap BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00002999
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003000 /// \brief The worst of the best N edit distances found so far.
3001 unsigned MaxEditDistance;
3002
3003 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003004
Douglas Gregor2d435302009-12-30 17:04:44 +00003005public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003006 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003007 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003008 MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3009 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003010
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003011 ~TypoCorrectionConsumer() {
3012 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3013 IEnd = BestResults.end();
3014 I != IEnd;
3015 ++I)
3016 delete I->second;
3017 }
3018
Douglas Gregor09bbc652010-01-14 15:47:35 +00003019 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003020 void FoundName(llvm::StringRef Name);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003021 void addKeywordResult(llvm::StringRef Keyword);
3022 void addName(llvm::StringRef Name, NamedDecl *ND, unsigned Distance,
3023 NestedNameSpecifier *NNS=NULL);
3024 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003025
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003026 typedef TypoResultsMap::iterator result_iterator;
3027 typedef TypoEditDistanceMap::iterator distance_iterator;
3028 distance_iterator begin() { return BestResults.begin(); }
3029 distance_iterator end() { return BestResults.end(); }
3030 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003031 unsigned size() const { return BestResults.size(); }
3032 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003033
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003034 TypoCorrection &operator[](llvm::StringRef Name) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003035 return (*BestResults.begin()->second)[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003036 }
3037
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003038 unsigned getMaxEditDistance() const {
3039 return MaxEditDistance;
3040 }
3041
3042 unsigned getBestEditDistance() {
3043 return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3044 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003045};
3046
3047}
3048
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003049void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003050 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003051 // Don't consider hidden names for typo correction.
3052 if (Hiding)
3053 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003054
Douglas Gregor2d435302009-12-30 17:04:44 +00003055 // Only consider entities with identifiers for names, ignoring
3056 // special names (constructors, overloaded operators, selectors,
3057 // etc.).
3058 IdentifierInfo *Name = ND->getIdentifier();
3059 if (!Name)
3060 return;
3061
Douglas Gregor57756ea2010-10-14 22:11:03 +00003062 FoundName(Name->getName());
3063}
3064
3065void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003066 // Use a simple length-based heuristic to determine the minimum possible
3067 // edit distance. If the minimum isn't good enough, bail out early.
3068 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003069 if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
Douglas Gregor93910a52010-10-19 19:39:10 +00003070 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003071
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003072 // Compute an upper bound on the allowable edit distance, so that the
3073 // edit-distance algorithm can short-circuit.
Jay Foad72e705e2011-04-23 09:06:00 +00003074 unsigned UpperBound =
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003075 std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076
Douglas Gregor2d435302009-12-30 17:04:44 +00003077 // Compute the edit distance between the typo and the name of this
3078 // entity. If this edit distance is not worse than the best edit
3079 // distance we've seen so far, add it to the list of results.
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003080 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003081
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003082 if (ED > MaxEditDistance) {
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003083 // This result is worse than the best results we've seen so far;
3084 // ignore it.
3085 return;
3086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003087
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003088 addName(Name, NULL, ED);
Douglas Gregor2d435302009-12-30 17:04:44 +00003089}
3090
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003091void TypoCorrectionConsumer::addKeywordResult(llvm::StringRef Keyword) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003092 // Compute the edit distance between the typo and this keyword.
3093 // If this edit distance is not worse than the best edit
3094 // distance we've seen so far, add it to the list of results.
3095 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003096 if (ED > MaxEditDistance) {
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003097 // This result is worse than the best results we've seen so far;
3098 // ignore it.
3099 return;
3100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003102 addName(Keyword, TypoCorrection::KeywordDecl(), ED);
3103}
3104
3105void TypoCorrectionConsumer::addName(llvm::StringRef Name,
3106 NamedDecl *ND,
3107 unsigned Distance,
3108 NestedNameSpecifier *NNS) {
3109 addCorrection(TypoCorrection(&SemaRef.Context.Idents.get(Name),
3110 ND, NNS, Distance));
3111}
3112
3113void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3114 llvm::StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003115 TypoResultsMap *& Map = BestResults[Correction.getEditDistance()];
3116 if (!Map)
3117 Map = new TypoResultsMap;
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003118
3119 TypoCorrection &CurrentCorrection = (*Map)[Name];
3120 if (!CurrentCorrection ||
3121 // FIXME: The following should be rolled up into an operator< on
3122 // TypoCorrection with a more principled definition.
3123 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3124 Correction.getAsString(SemaRef.getLangOptions()) <
3125 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3126 CurrentCorrection = Correction;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003127
3128 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003129 TypoEditDistanceMap::iterator Last = BestResults.end();
3130 --Last;
3131 delete Last->second;
3132 BestResults.erase(Last);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003133 }
3134}
3135
3136namespace {
3137
3138class SpecifierInfo {
3139 public:
3140 DeclContext* DeclCtx;
3141 NestedNameSpecifier* NameSpecifier;
3142 unsigned EditDistance;
3143
3144 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3145 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3146};
3147
3148typedef llvm::SmallVector<DeclContext*, 4> DeclContextList;
3149typedef llvm::SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3150
3151class NamespaceSpecifierSet {
3152 ASTContext &Context;
3153 DeclContextList CurContextChain;
3154 bool isSorted;
3155
3156 SpecifierInfoList Specifiers;
3157 llvm::SmallSetVector<unsigned, 4> Distances;
3158 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3159
3160 /// \brief Helper for building the list of DeclContexts between the current
3161 /// context and the top of the translation unit
3162 static DeclContextList BuildContextChain(DeclContext *Start);
3163
3164 void SortNamespaces();
3165
3166 public:
3167 explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003168 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3169 isSorted(true) {}
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003170
3171 /// \brief Add the namespace to the set, computing the corresponding
3172 /// NestedNameSpecifier and its distance in the process.
3173 void AddNamespace(NamespaceDecl *ND);
3174
3175 typedef SpecifierInfoList::iterator iterator;
3176 iterator begin() {
3177 if (!isSorted) SortNamespaces();
3178 return Specifiers.begin();
3179 }
3180 iterator end() { return Specifiers.end(); }
3181};
3182
3183}
3184
3185DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003186 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003187 DeclContextList Chain;
3188 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3189 DC = DC->getLookupParent()) {
3190 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3191 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3192 !(ND && ND->isAnonymousNamespace()))
3193 Chain.push_back(DC->getPrimaryContext());
3194 }
3195 return Chain;
3196}
3197
3198void NamespaceSpecifierSet::SortNamespaces() {
3199 llvm::SmallVector<unsigned, 4> sortedDistances;
3200 sortedDistances.append(Distances.begin(), Distances.end());
3201
3202 if (sortedDistances.size() > 1)
3203 std::sort(sortedDistances.begin(), sortedDistances.end());
3204
3205 Specifiers.clear();
3206 for (llvm::SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
3207 DIEnd = sortedDistances.end();
3208 DI != DIEnd; ++DI) {
3209 SpecifierInfoList &SpecList = DistanceMap[*DI];
3210 Specifiers.append(SpecList.begin(), SpecList.end());
3211 }
3212
3213 isSorted = true;
3214}
3215
3216void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003217 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003218 NestedNameSpecifier *NNS = NULL;
3219 unsigned NumSpecifiers = 0;
3220 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3221
3222 // Eliminate common elements from the two DeclContext chains
3223 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3224 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003225 C != CEnd && !NamespaceDeclChain.empty() &&
3226 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003227 NamespaceDeclChain.pop_back();
3228 }
3229
3230 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3231 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3232 CEnd = NamespaceDeclChain.rend();
3233 C != CEnd; ++C) {
3234 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3235 if (ND) {
3236 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3237 ++NumSpecifiers;
3238 }
3239 }
3240
3241 isSorted = false;
3242 Distances.insert(NumSpecifiers);
3243 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003244}
3245
Douglas Gregord507d772010-10-20 03:06:34 +00003246/// \brief Perform name lookup for a possible result for typo correction.
3247static void LookupPotentialTypoResult(Sema &SemaRef,
3248 LookupResult &Res,
3249 IdentifierInfo *Name,
3250 Scope *S, CXXScopeSpec *SS,
3251 DeclContext *MemberContext,
3252 bool EnteringContext,
3253 Sema::CorrectTypoContext CTC) {
3254 Res.suppressDiagnostics();
3255 Res.clear();
3256 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003258 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3259 if (CTC == Sema::CTC_ObjCIvarLookup) {
3260 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3261 Res.addDecl(Ivar);
3262 Res.resolveKind();
3263 return;
3264 }
3265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266
Douglas Gregord507d772010-10-20 03:06:34 +00003267 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3268 Res.addDecl(Prop);
3269 Res.resolveKind();
3270 return;
3271 }
3272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273
Douglas Gregord507d772010-10-20 03:06:34 +00003274 SemaRef.LookupQualifiedName(Res, MemberContext);
3275 return;
3276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003277
3278 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003279 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280
Douglas Gregord507d772010-10-20 03:06:34 +00003281 // Fake ivar lookup; this should really be part of
3282 // LookupParsedName.
3283 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3284 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003285 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003286 (Res.isSingleResult() &&
3287 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003289 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3290 Res.addDecl(IV);
3291 Res.resolveKind();
3292 }
3293 }
3294 }
3295}
3296
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003297/// \brief Add keywords to the consumer as possible typo corrections.
3298static void AddKeywordsToConsumer(Sema &SemaRef,
3299 TypoCorrectionConsumer &Consumer,
3300 Scope *S, Sema::CorrectTypoContext CTC) {
3301 // Add context-dependent keywords.
3302 bool WantTypeSpecifiers = false;
3303 bool WantExpressionKeywords = false;
3304 bool WantCXXNamedCasts = false;
3305 bool WantRemainingKeywords = false;
3306 switch (CTC) {
3307 case Sema::CTC_Unknown:
3308 WantTypeSpecifiers = true;
3309 WantExpressionKeywords = true;
3310 WantCXXNamedCasts = true;
3311 WantRemainingKeywords = true;
3312
3313 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3314 if (Method->getClassInterface() &&
3315 Method->getClassInterface()->getSuperClass())
3316 Consumer.addKeywordResult("super");
3317
3318 break;
3319
3320 case Sema::CTC_NoKeywords:
3321 break;
3322
3323 case Sema::CTC_Type:
3324 WantTypeSpecifiers = true;
3325 break;
3326
3327 case Sema::CTC_ObjCMessageReceiver:
3328 Consumer.addKeywordResult("super");
3329 // Fall through to handle message receivers like expressions.
3330
3331 case Sema::CTC_Expression:
3332 if (SemaRef.getLangOptions().CPlusPlus)
3333 WantTypeSpecifiers = true;
3334 WantExpressionKeywords = true;
3335 // Fall through to get C++ named casts.
3336
3337 case Sema::CTC_CXXCasts:
3338 WantCXXNamedCasts = true;
3339 break;
3340
3341 case Sema::CTC_ObjCPropertyLookup:
3342 // FIXME: Add "isa"?
3343 break;
3344
3345 case Sema::CTC_MemberLookup:
3346 if (SemaRef.getLangOptions().CPlusPlus)
3347 Consumer.addKeywordResult("template");
3348 break;
3349
3350 case Sema::CTC_ObjCIvarLookup:
3351 break;
3352 }
3353
3354 if (WantTypeSpecifiers) {
3355 // Add type-specifier keywords to the set of results.
3356 const char *CTypeSpecs[] = {
3357 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003358 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003359 "_Complex", "_Imaginary",
3360 // storage-specifiers as well
3361 "extern", "inline", "static", "typedef"
3362 };
3363
3364 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3365 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3366 Consumer.addKeywordResult(CTypeSpecs[I]);
3367
3368 if (SemaRef.getLangOptions().C99)
3369 Consumer.addKeywordResult("restrict");
3370 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3371 Consumer.addKeywordResult("bool");
Douglas Gregor3b22a882011-07-01 21:27:45 +00003372 else if (SemaRef.getLangOptions().C99)
3373 Consumer.addKeywordResult("_Bool");
3374
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003375 if (SemaRef.getLangOptions().CPlusPlus) {
3376 Consumer.addKeywordResult("class");
3377 Consumer.addKeywordResult("typename");
3378 Consumer.addKeywordResult("wchar_t");
3379
3380 if (SemaRef.getLangOptions().CPlusPlus0x) {
3381 Consumer.addKeywordResult("char16_t");
3382 Consumer.addKeywordResult("char32_t");
3383 Consumer.addKeywordResult("constexpr");
3384 Consumer.addKeywordResult("decltype");
3385 Consumer.addKeywordResult("thread_local");
3386 }
3387 }
3388
3389 if (SemaRef.getLangOptions().GNUMode)
3390 Consumer.addKeywordResult("typeof");
3391 }
3392
3393 if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3394 Consumer.addKeywordResult("const_cast");
3395 Consumer.addKeywordResult("dynamic_cast");
3396 Consumer.addKeywordResult("reinterpret_cast");
3397 Consumer.addKeywordResult("static_cast");
3398 }
3399
3400 if (WantExpressionKeywords) {
3401 Consumer.addKeywordResult("sizeof");
3402 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3403 Consumer.addKeywordResult("false");
3404 Consumer.addKeywordResult("true");
3405 }
3406
3407 if (SemaRef.getLangOptions().CPlusPlus) {
3408 const char *CXXExprs[] = {
3409 "delete", "new", "operator", "throw", "typeid"
3410 };
3411 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3412 for (unsigned I = 0; I != NumCXXExprs; ++I)
3413 Consumer.addKeywordResult(CXXExprs[I]);
3414
3415 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3416 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3417 Consumer.addKeywordResult("this");
3418
3419 if (SemaRef.getLangOptions().CPlusPlus0x) {
3420 Consumer.addKeywordResult("alignof");
3421 Consumer.addKeywordResult("nullptr");
3422 }
3423 }
3424 }
3425
3426 if (WantRemainingKeywords) {
3427 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3428 // Statements.
3429 const char *CStmts[] = {
3430 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3431 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3432 for (unsigned I = 0; I != NumCStmts; ++I)
3433 Consumer.addKeywordResult(CStmts[I]);
3434
3435 if (SemaRef.getLangOptions().CPlusPlus) {
3436 Consumer.addKeywordResult("catch");
3437 Consumer.addKeywordResult("try");
3438 }
3439
3440 if (S && S->getBreakParent())
3441 Consumer.addKeywordResult("break");
3442
3443 if (S && S->getContinueParent())
3444 Consumer.addKeywordResult("continue");
3445
3446 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3447 Consumer.addKeywordResult("case");
3448 Consumer.addKeywordResult("default");
3449 }
3450 } else {
3451 if (SemaRef.getLangOptions().CPlusPlus) {
3452 Consumer.addKeywordResult("namespace");
3453 Consumer.addKeywordResult("template");
3454 }
3455
3456 if (S && S->isClassScope()) {
3457 Consumer.addKeywordResult("explicit");
3458 Consumer.addKeywordResult("friend");
3459 Consumer.addKeywordResult("mutable");
3460 Consumer.addKeywordResult("private");
3461 Consumer.addKeywordResult("protected");
3462 Consumer.addKeywordResult("public");
3463 Consumer.addKeywordResult("virtual");
3464 }
3465 }
3466
3467 if (SemaRef.getLangOptions().CPlusPlus) {
3468 Consumer.addKeywordResult("using");
3469
3470 if (SemaRef.getLangOptions().CPlusPlus0x)
3471 Consumer.addKeywordResult("static_assert");
3472 }
3473 }
3474}
3475
Douglas Gregor2d435302009-12-30 17:04:44 +00003476/// \brief Try to "correct" a typo in the source code by finding
3477/// visible declarations whose names are similar to the name that was
3478/// present in the source code.
3479///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003480/// \param TypoName the \c DeclarationNameInfo structure that contains
3481/// the name that was present in the source code along with its location.
3482///
3483/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003484///
3485/// \param S the scope in which name lookup occurs.
3486///
3487/// \param SS the nested-name-specifier that precedes the name we're
3488/// looking for, if present.
3489///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003490/// \param MemberContext if non-NULL, the context in which to look for
3491/// a member access expression.
3492///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003494/// the nested-name-specifier SS.
3495///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003496/// \param CTC The context in which typo correction occurs, which impacts the
3497/// set of keywords permitted.
3498///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003499/// \param OPT when non-NULL, the search for visible declarations will
3500/// also walk the protocols in the qualified interfaces of \p OPT.
3501///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003502/// \returns a \c TypoCorrection containing the corrected name if the typo
3503/// along with information such as the \c NamedDecl where the corrected name
3504/// was declared, and any additional \c NestedNameSpecifier needed to access
3505/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3506TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3507 Sema::LookupNameKind LookupKind,
3508 Scope *S, CXXScopeSpec *SS,
3509 DeclContext *MemberContext,
3510 bool EnteringContext,
3511 CorrectTypoContext CTC,
3512 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00003513 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003514 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515
Douglas Gregor2d435302009-12-30 17:04:44 +00003516 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003517 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003518 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003519 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003520
3521 // If the scope specifier itself was invalid, don't try to correct
3522 // typos.
3523 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003524 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003525
3526 // Never try to correct typos during template deduction or
3527 // instantiation.
3528 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003529 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003530
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003531 NamespaceSpecifierSet Namespaces(Context, CurContext);
3532
3533 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003535 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003536 bool IsUnqualifiedLookup = false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003537 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003538 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003539
3540 // Look in qualified interfaces.
3541 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542 for (ObjCObjectPointerType::qual_iterator
3543 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003544 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003545 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003546 }
3547 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003548 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3549 if (!DC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003550 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Douglas Gregor87074f12010-10-20 01:32:02 +00003552 // Provide a stop gap for files that are just seriously broken. Trying
3553 // to correct all typos can turn into a HUGE performance penalty, causing
3554 // some files to take minutes to get rejected by the parser.
3555 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003556 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003557 ++TyposCorrected;
3558
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003559 LookupVisibleDecls(DC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003560 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003561 IsUnqualifiedLookup = true;
3562 UnqualifiedTyposCorrectedMap::iterator Cached
3563 = UnqualifiedTyposCorrected.find(Typo);
3564 if (Cached == UnqualifiedTyposCorrected.end()) {
3565 // Provide a stop gap for files that are just seriously broken. Trying
3566 // to correct all typos can turn into a HUGE performance penalty, causing
3567 // some files to take minutes to get rejected by the parser.
3568 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003569 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003570
Douglas Gregor87074f12010-10-20 01:32:02 +00003571 // For unqualified lookup, look through all of the names that we have
3572 // seen in this translation unit.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor87074f12010-10-20 01:32:02 +00003574 IEnd = Context.Idents.end();
3575 I != IEnd; ++I)
3576 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577
Douglas Gregor87074f12010-10-20 01:32:02 +00003578 // Walk through identifiers in external identifier sources.
3579 if (IdentifierInfoLookup *External
Douglas Gregor57756ea2010-10-14 22:11:03 +00003580 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenekb4ea9a82010-11-07 06:11:33 +00003581 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor87074f12010-10-20 01:32:02 +00003582 do {
3583 llvm::StringRef Name = Iter->Next();
3584 if (Name.empty())
3585 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003586
Douglas Gregor87074f12010-10-20 01:32:02 +00003587 Consumer.FoundName(Name);
3588 } while (true);
3589 }
3590 } else {
3591 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3592 // end up adding the keyword below.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003593 if (!Cached->second)
3594 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003596 if (!Cached->second.isKeyword())
3597 Consumer.addCorrection(Cached->second);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003598 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003599 }
3600
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003601 AddKeywordsToConsumer(*this, Consumer, S, CTC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003603 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003604 if (Consumer.empty()) {
3605 // If this was an unqualified lookup, note that no correction was found.
3606 if (IsUnqualifiedLookup)
3607 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003609 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003610 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003611
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003613 // made. Otherwise, we don't even both looking at the results.
3614 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor87074f12010-10-20 01:32:02 +00003615 if (ED > 0 && Typo->getName().size() / ED < 3) {
3616 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003617 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003618 (void)UnqualifiedTyposCorrected[Typo];
3619
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003620 return TypoCorrection();
3621 }
3622
3623 // Build the NestedNameSpecifiers for the KnownNamespaces
3624 if (getLangOptions().CPlusPlus) {
3625 // Load any externally-known namespaces.
3626 if (ExternalSource && !LoadedExternalKnownNamespaces) {
3627 llvm::SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
3628 LoadedExternalKnownNamespaces = true;
3629 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3630 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3631 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3632 }
3633
3634 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3635 KNI = KnownNamespaces.begin(),
3636 KNIEnd = KnownNamespaces.end();
3637 KNI != KNIEnd; ++KNI)
3638 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003639 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003640
3641 // Weed out any names that could not be found by name lookup.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003642 llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3643 LookupResult TmpRes(*this, TypoName, LookupKind);
3644 TmpRes.suppressDiagnostics();
3645 while (!Consumer.empty()) {
3646 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3647 unsigned ED = DI->first;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003648 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3649 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003650 I != IEnd; /* Increment in loop. */) {
3651 // If the item already has been looked up or is a keyword, keep it
3652 if (I->second.isResolved()) {
3653 ++I;
3654 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003656
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003657 // Perform name lookup on this name.
3658 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3659 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3660 EnteringContext, CTC);
3661
3662 switch (TmpRes.getResultKind()) {
3663 case LookupResult::NotFound:
3664 case LookupResult::NotFoundInCurrentInstantiation:
3665 QualifiedResults.insert(Name);
3666 // We didn't find this name in our scope, or didn't like what we found;
3667 // ignore it.
3668 {
3669 TypoCorrectionConsumer::result_iterator Next = I;
3670 ++Next;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003671 DI->second->erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003672 I = Next;
3673 }
3674 break;
3675
3676 case LookupResult::Ambiguous:
3677 // We don't deal with ambiguities.
3678 return TypoCorrection();
3679
3680 case LookupResult::Found:
3681 case LookupResult::FoundOverloaded:
3682 case LookupResult::FoundUnresolvedValue:
3683 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Hans Wennborg38198de2011-07-12 08:45:31 +00003684 // FIXME: This sets the CorrectionDecl to NULL for overloaded functions.
3685 // It would be nice to find the right one with overload resolution.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003686 ++I;
3687 break;
3688 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003690
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003691 if (DI->second->empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003692 Consumer.erase(DI);
3693 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3694 // If there are results in the closest possible bucket, stop
3695 break;
3696
3697 // Only perform the qualified lookups for C++
3698 if (getLangOptions().CPlusPlus) {
3699 TmpRes.suppressDiagnostics();
3700 for (llvm::SmallPtrSet<IdentifierInfo*,
3701 16>::iterator QRI = QualifiedResults.begin(),
3702 QRIEnd = QualifiedResults.end();
3703 QRI != QRIEnd; ++QRI) {
3704 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3705 NIEnd = Namespaces.end();
3706 NI != NIEnd; ++NI) {
3707 DeclContext *Ctx = NI->DeclCtx;
3708 unsigned QualifiedED = ED + NI->EditDistance;
3709
3710 // Stop searching once the namespaces are too far away to create
3711 // acceptable corrections for this identifier (since the namespaces
3712 // are sorted in ascending order by edit distance)
3713 if (QualifiedED > Consumer.getMaxEditDistance()) break;
3714
3715 TmpRes.clear();
3716 TmpRes.setLookupName(*QRI);
3717 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3718
3719 switch (TmpRes.getResultKind()) {
3720 case LookupResult::Found:
3721 case LookupResult::FoundOverloaded:
3722 case LookupResult::FoundUnresolvedValue:
3723 Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3724 QualifiedED, NI->NameSpecifier);
3725 break;
3726 case LookupResult::NotFound:
3727 case LookupResult::NotFoundInCurrentInstantiation:
3728 case LookupResult::Ambiguous:
3729 break;
3730 }
3731 }
3732 }
3733 }
3734
3735 QualifiedResults.clear();
3736 }
3737
3738 // No corrections remain...
3739 if (Consumer.empty()) return TypoCorrection();
3740
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003741 TypoResultsMap &BestResults = *Consumer.begin()->second;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003742 ED = Consumer.begin()->first;
3743
3744 if (ED > 0 && Typo->getName().size() / ED < 3) {
3745 // If this was an unqualified lookup, note that no correction was found.
3746 if (IsUnqualifiedLookup)
3747 (void)UnqualifiedTyposCorrected[Typo];
3748
3749 return TypoCorrection();
3750 }
3751
3752 // If we have multiple possible corrections, eliminate the ones where we
3753 // added namespace qualifiers to try to resolve the ambiguity (and to favor
3754 // corrections without additional namespace qualifiers)
3755 if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3756 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003757 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3758 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003759 I != IEnd; /* Increment in loop. */) {
3760 if (I->second.getCorrectionSpecifier() != NULL) {
3761 TypoCorrectionConsumer::result_iterator Cur = I;
3762 ++I;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003763 DI->second->erase(Cur);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003764 } else ++I;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003765 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003766 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003767
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003768 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003769 if (BestResults.size() == 1) {
3770 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3771 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003773 // Don't correct to a keyword that's the same as the typo; the keyword
3774 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003775 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3776
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003777 // Record the correction for unqualified lookup.
3778 if (IsUnqualifiedLookup)
3779 UnqualifiedTyposCorrected[Typo] = Result;
3780
3781 return Result;
3782 }
3783 else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3784 && BestResults["super"].isKeyword()) {
3785 // Prefer 'super' when we're completing in a message-receiver
3786 // context.
3787
3788 // Don't correct to a keyword that's the same as the typo; the keyword
3789 // wasn't actually in scope.
3790 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791
Douglas Gregor87074f12010-10-20 01:32:02 +00003792 // Record the correction for unqualified lookup.
3793 if (IsUnqualifiedLookup)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003794 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003796 return BestResults["super"];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003797 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003798
Douglas Gregor87074f12010-10-20 01:32:02 +00003799 if (IsUnqualifiedLookup)
3800 (void)UnqualifiedTyposCorrected[Typo];
3801
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003802 return TypoCorrection();
3803}
3804
3805std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3806 if (CorrectionNameSpec) {
3807 std::string tmpBuffer;
3808 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3809 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3810 return PrefixOStream.str() + CorrectionName.getAsString();
3811 }
3812
3813 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00003814}