blob: c232515ef365623da3d8e11e4a991034f0341001 [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 {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000090 typedef 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) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000151 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000152 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
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464void LookupResult::print(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
Sebastian Redl22653ba2011-08-30 19:58:05 +0000553 if (getLangOptions().CPlusPlus0x) {
554 // If the move constructor has not yet been declared, do so now.
555 if (Class->needsImplicitMoveConstructor())
556 DeclareImplicitMoveConstructor(Class); // might not actually do it
557
558 // If the move assignment operator has not yet been declared, do so now.
559 if (Class->needsImplicitMoveAssignment())
560 DeclareImplicitMoveAssignment(Class); // might not actually do it
561 }
562
Douglas Gregor7454c562010-07-02 20:37:36 +0000563 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000564 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000566}
567
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000569/// special member function.
570static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
571 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000572 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000573 case DeclarationName::CXXDestructorName:
574 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000576 case DeclarationName::CXXOperatorName:
577 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000579 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000583 return false;
584}
585
586/// \brief If there are any implicit member functions with the given name
587/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000589 DeclarationName Name,
590 const DeclContext *DC) {
591 if (!DC)
592 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000594 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000595 case DeclarationName::CXXConstructorName:
596 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000597 if (Record->getDefinition() &&
598 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000599 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000600 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000601 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000602 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000603 S.DeclareImplicitCopyConstructor(Class);
604 if (S.getLangOptions().CPlusPlus0x &&
605 Record->needsImplicitMoveConstructor())
606 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000607 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000610 case DeclarationName::CXXDestructorName:
611 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
612 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
613 CanDeclareSpecialMemberFunction(S.Context, Record))
614 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000617 case DeclarationName::CXXOperatorName:
618 if (Name.getCXXOverloadedOperator() != OO_Equal)
619 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620
Sebastian Redl22653ba2011-08-30 19:58:05 +0000621 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
622 if (Record->getDefinition() &&
623 CanDeclareSpecialMemberFunction(S.Context, Record)) {
624 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
625 if (!Record->hasDeclaredCopyAssignment())
626 S.DeclareImplicitCopyAssignment(Class);
627 if (S.getLangOptions().CPlusPlus0x &&
628 Record->needsImplicitMoveAssignment())
629 S.DeclareImplicitMoveAssignment(Class);
630 }
631 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000632 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000634 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000635 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000636 }
637}
Douglas Gregor7454c562010-07-02 20:37:36 +0000638
John McCall9f3059a2009-10-09 21:13:30 +0000639// Adds all qualifying matches for a name within a decl context to the
640// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000641static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000642 bool Found = false;
643
Douglas Gregor7454c562010-07-02 20:37:36 +0000644 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000645 if (S.getLangOptions().CPlusPlus)
646 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000647
Douglas Gregor7454c562010-07-02 20:37:36 +0000648 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000649 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000650 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000651 NamedDecl *D = *I;
652 if (R.isAcceptableDecl(D)) {
653 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000654 Found = true;
655 }
656 }
John McCall9f3059a2009-10-09 21:13:30 +0000657
Douglas Gregord3a59182010-02-12 05:48:04 +0000658 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
659 return true;
660
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000661 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000662 != DeclarationName::CXXConversionFunctionName ||
663 R.getLookupName().getCXXNameType()->isDependentType() ||
664 !isa<CXXRecordDecl>(DC))
665 return Found;
666
667 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000668 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000669 // name lookup. Instead, any conversion function templates visible in the
670 // context of the use are considered. [...]
671 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000672 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000673 return Found;
674
675 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000676 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000677 UEnd = Unresolved->end(); U != UEnd; ++U) {
678 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
679 if (!ConvTemplate)
680 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681
Chandler Carruth3a693b72010-01-31 11:44:02 +0000682 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683 // add the conversion function template. When we deduce template
684 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000685 // type of the new declaration with the type of the function template.
686 if (R.isForRedeclaration()) {
687 R.addDecl(ConvTemplate);
688 Found = true;
689 continue;
690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000692 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693 // [...] For each such operator, if argument deduction succeeds
694 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000695 // name lookup.
696 //
697 // When referencing a conversion function for any purpose other than
698 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000700 // specialization into the result set. We do this to avoid forcing all
701 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000702 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000703 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
705 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000706 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
707 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000708
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709 // Compute the type of the function that we would expect the conversion
710 // function to have, if it were to match the name given.
711 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000712 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
713 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000714 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000715 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000716 QualType ExpectedType
717 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000718 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000719
Chandler Carruth3a693b72010-01-31 11:44:02 +0000720 // Perform template argument deduction against the type that we would
721 // expect the function to have.
722 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
723 Specialization, Info)
724 == Sema::TDK_Success) {
725 R.addDecl(Specialization);
726 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000727 }
728 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000729
John McCall9f3059a2009-10-09 21:13:30 +0000730 return Found;
731}
732
John McCallf6c8a4e2009-11-10 07:01:13 +0000733// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000734static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000736 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000737
738 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
739
John McCallf6c8a4e2009-11-10 07:01:13 +0000740 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000741 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000742
John McCallf6c8a4e2009-11-10 07:01:13 +0000743 // Perform direct name lookup into the namespaces nominated by the
744 // using directives whose common ancestor is this namespace.
745 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
746 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000747
John McCallf6c8a4e2009-11-10 07:01:13 +0000748 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000749 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000750 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000751
752 R.resolveKind();
753
754 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000755}
756
757static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000758 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000759 return Ctx->isFileContext();
760 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000761}
Douglas Gregored8f2882009-01-30 01:04:22 +0000762
Douglas Gregor66230062010-03-15 14:33:29 +0000763// Find the next outer declaration context from this scope. This
764// routine actually returns the semantic outer context, which may
765// differ from the lexical context (encoded directly in the Scope
766// stack) when we are parsing a member of a class template. In this
767// case, the second element of the pair will be true, to indicate that
768// name lookup should continue searching in this semantic context when
769// it leaves the current template parameter scope.
770static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
771 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
772 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000774 OuterS = OuterS->getParent()) {
775 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000776 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000777 break;
778 }
779 }
780
781 // C++ [temp.local]p8:
782 // In the definition of a member of a class template that appears
783 // outside of the namespace containing the class template
784 // definition, the name of a template-parameter hides the name of
785 // a member of this namespace.
786 //
787 // Example:
788 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789 // namespace N {
790 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000791 //
792 // template<class T> class B {
793 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000795 // }
796 //
797 // template<class C> void N::B<C>::f(C) {
798 // C b; // C is the template parameter, not N::C
799 // }
800 //
801 // In this example, the lexical context we return is the
802 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000803 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000804 !S->getParent()->isTemplateParamScope())
805 return std::make_pair(Lexical, false);
806
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000808 // For the example, this is the scope for the template parameters of
809 // template<class C>.
810 Scope *OutermostTemplateScope = S->getParent();
811 while (OutermostTemplateScope->getParent() &&
812 OutermostTemplateScope->getParent()->isTemplateParamScope())
813 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814
Douglas Gregor66230062010-03-15 14:33:29 +0000815 // Find the namespace context in which the original scope occurs. In
816 // the example, this is namespace N.
817 DeclContext *Semantic = DC;
818 while (!Semantic->isFileContext())
819 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregor66230062010-03-15 14:33:29 +0000821 // Find the declaration context just outside of the template
822 // parameter scope. This is the context in which the template is
823 // being lexically declaration (a namespace context). In the
824 // example, this is the global scope.
825 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
826 Lexical->Encloses(Semantic))
827 return std::make_pair(Semantic, true);
828
829 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000830}
831
John McCall27b18f82009-11-17 02:14:36 +0000832bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000833 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000834
835 DeclarationName Name = R.getLookupName();
836
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000837 // If this is the name of an implicitly-declared special member function,
838 // go through the scope stack to implicitly declare
839 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
840 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
841 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
842 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000845 // Implicitly declare member functions with the name we're looking for, if in
846 // fact we are in a scope where it matters.
847
Douglas Gregor889ceb72009-02-03 19:21:40 +0000848 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000849 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000850 I = IdResolver.begin(Name),
851 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000852
Douglas Gregor889ceb72009-02-03 19:21:40 +0000853 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000854 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000855 // ...During unqualified name lookup (3.4.1), the names appear as if
856 // they were declared in the nearest enclosing namespace which contains
857 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000858 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000859 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000860 //
861 // For example:
862 // namespace A { int i; }
863 // void foo() {
864 // int i;
865 // {
866 // using namespace A;
867 // ++i; // finds local 'i', A::i appears at global scope
868 // }
869 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000870 //
Douglas Gregor66230062010-03-15 14:33:29 +0000871 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000872 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000873 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
874
Douglas Gregor889ceb72009-02-03 19:21:40 +0000875 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000876 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000877 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000878 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000879 Found = true;
880 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000881 }
882 }
John McCall9f3059a2009-10-09 21:13:30 +0000883 if (Found) {
884 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000885 if (S->isClassScope())
886 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
887 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000888 return true;
889 }
890
Douglas Gregor66230062010-03-15 14:33:29 +0000891 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
892 S->getParent() && !S->getParent()->isTemplateParamScope()) {
893 // We've just searched the last template parameter scope and
894 // found nothing, so look into the the contexts between the
895 // lexical and semantic declaration contexts returned by
896 // findOuterContext(). This implements the name lookup behavior
897 // of C++ [temp.local]p8.
898 Ctx = OutsideOfTemplateParamDC;
899 OutsideOfTemplateParamDC = 0;
900 }
901
902 if (Ctx) {
903 DeclContext *OuterCtx;
904 bool SearchAfterTemplateScope;
905 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
906 if (SearchAfterTemplateScope)
907 OutsideOfTemplateParamDC = OuterCtx;
908
Douglas Gregorea166062010-03-15 15:26:48 +0000909 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000910 // We do not directly look into transparent contexts, since
911 // those entities will be found in the nearest enclosing
912 // non-transparent context.
913 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000914 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000915
916 // We do not look directly into function or method contexts,
917 // since all of the local variables and parameters of the
918 // function/method are present within the Scope.
919 if (Ctx->isFunctionOrMethod()) {
920 // If we have an Objective-C instance method, look for ivars
921 // in the corresponding interface.
922 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
923 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
924 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
925 ObjCInterfaceDecl *ClassDeclared;
926 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000928 ClassDeclared)) {
929 if (R.isAcceptableDecl(Ivar)) {
930 R.addDecl(Ivar);
931 R.resolveKind();
932 return true;
933 }
934 }
935 }
936 }
937
938 continue;
939 }
940
Douglas Gregor7f737c02009-09-10 16:57:35 +0000941 // Perform qualified name lookup into this context.
942 // FIXME: In some cases, we know that every name that could be found by
943 // this qualified name lookup will also be on the identifier chain. For
944 // example, inside a class without any base classes, we never need to
945 // perform qualified lookup because all of the members are on top of the
946 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000947 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000948 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000949 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000950 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000951 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000952
John McCallf6c8a4e2009-11-10 07:01:13 +0000953 // Stop if we ran out of scopes.
954 // FIXME: This really, really shouldn't be happening.
955 if (!S) return false;
956
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000957 // If we are looking for members, no need to look into global/namespace scope.
958 if (R.getLookupKind() == LookupMemberName)
959 return false;
960
Douglas Gregor700792c2009-02-05 19:25:20 +0000961 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000962 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000963 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000964 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
965 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000966
John McCallf6c8a4e2009-11-10 07:01:13 +0000967 UnqualUsingDirectiveSet UDirs;
968 UDirs.visitScopeChain(Initial, S);
969 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000970
Douglas Gregor700792c2009-02-05 19:25:20 +0000971 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000972 // Unqualified name lookup in C++ requires looking into scopes
973 // that aren't strictly lexical, and therefore we walk through the
974 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000975
Douglas Gregor889ceb72009-02-03 19:21:40 +0000976 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000977 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000978 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000979 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000980 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000981 // We found something. Look for anything else in our scope
982 // with this same name and in an acceptable identifier
983 // namespace, so that we can construct an overload set if we
984 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000985 Found = true;
986 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000987 }
988 }
989
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000990 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000991 R.resolveKind();
992 return true;
993 }
994
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000995 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
996 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
997 S->getParent() && !S->getParent()->isTemplateParamScope()) {
998 // We've just searched the last template parameter scope and
999 // found nothing, so look into the the contexts between the
1000 // lexical and semantic declaration contexts returned by
1001 // findOuterContext(). This implements the name lookup behavior
1002 // of C++ [temp.local]p8.
1003 Ctx = OutsideOfTemplateParamDC;
1004 OutsideOfTemplateParamDC = 0;
1005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001007 if (Ctx) {
1008 DeclContext *OuterCtx;
1009 bool SearchAfterTemplateScope;
1010 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1011 if (SearchAfterTemplateScope)
1012 OutsideOfTemplateParamDC = OuterCtx;
1013
1014 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1015 // We do not directly look into transparent contexts, since
1016 // those entities will be found in the nearest enclosing
1017 // non-transparent context.
1018 if (Ctx->isTransparentContext())
1019 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001021 // If we have a context, and it's not a context stashed in the
1022 // template parameter scope for an out-of-line definition, also
1023 // look into that context.
1024 if (!(Found && S && S->isTemplateParamScope())) {
1025 assert(Ctx->isFileContext() &&
1026 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001028 // Look into context considering using-directives.
1029 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1030 Found = true;
1031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001032
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001033 if (Found) {
1034 R.resolveKind();
1035 return true;
1036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001038 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1039 return false;
1040 }
1041 }
1042
Douglas Gregor3ce74932010-02-05 07:07:10 +00001043 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001044 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001045 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001046
John McCall9f3059a2009-10-09 21:13:30 +00001047 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001048}
1049
Douglas Gregor34074322009-01-14 22:20:51 +00001050/// @brief Perform unqualified name lookup starting from a given
1051/// scope.
1052///
1053/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1054/// used to find names within the current scope. For example, 'x' in
1055/// @code
1056/// int x;
1057/// int f() {
1058/// return x; // unqualified name look finds 'x' in the global scope
1059/// }
1060/// @endcode
1061///
1062/// Different lookup criteria can find different names. For example, a
1063/// particular scope can have both a struct and a function of the same
1064/// name, and each can be found by certain lookup criteria. For more
1065/// information about lookup criteria, see the documentation for the
1066/// class LookupCriteria.
1067///
1068/// @param S The scope from which unqualified name lookup will
1069/// begin. If the lookup criteria permits, name lookup may also search
1070/// in the parent scopes.
1071///
1072/// @param Name The name of the entity that we are searching for.
1073///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001074/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001075/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001076/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001077///
1078/// @returns The result of name lookup, which includes zero or more
1079/// declarations and possibly additional information used to diagnose
1080/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001081bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1082 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001083 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001084
John McCall27b18f82009-11-17 02:14:36 +00001085 LookupNameKind NameKind = R.getLookupKind();
1086
Douglas Gregor34074322009-01-14 22:20:51 +00001087 if (!getLangOptions().CPlusPlus) {
1088 // Unqualified name lookup in C/Objective-C is purely lexical, so
1089 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001090 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001091 // Find the nearest non-transparent declaration scope.
1092 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001093 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001094 static_cast<DeclContext *>(S->getEntity())
1095 ->isTransparentContext()))
1096 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001097 }
1098
John McCallea305ed2009-12-18 10:40:03 +00001099 unsigned IDNS = R.getIdentifierNamespace();
1100
Douglas Gregor34074322009-01-14 22:20:51 +00001101 // Scan up the scope chain looking for a decl that matches this
1102 // identifier that is in the appropriate namespace. This search
1103 // should not take long, as shadowing of names is uncommon, and
1104 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001105 bool LeftStartingScope = false;
1106
Douglas Gregored8f2882009-01-30 01:04:22 +00001107 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001108 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001109 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001110 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001111 if (NameKind == LookupRedeclarationWithLinkage) {
1112 // Determine whether this (or a previous) declaration is
1113 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001114 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001115 LeftStartingScope = true;
1116
1117 // If we found something outside of our starting scope that
1118 // does not have linkage, skip it.
1119 if (LeftStartingScope && !((*I)->hasLinkage()))
1120 continue;
1121 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001122 else if (NameKind == LookupObjCImplicitSelfParam &&
1123 !isa<ImplicitParamDecl>(*I))
1124 continue;
1125
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001126 // If this declaration is module-private and it came from an AST
1127 // file, we can't see it.
1128 if ((*I)->isModulePrivate() && (*I)->isFromASTFile())
1129 continue;
1130
John McCall9f3059a2009-10-09 21:13:30 +00001131 R.addDecl(*I);
1132
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001133 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001134 // If this declaration has the "overloadable" attribute, we
1135 // might have a set of overloaded functions.
1136
1137 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001138 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001139 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001140 S = S->getParent();
1141
1142 // Find the last declaration in this scope (with the same
1143 // name, naturally).
1144 IdentifierResolver::iterator LastI = I;
1145 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001146 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001147 break;
John McCall9f3059a2009-10-09 21:13:30 +00001148 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001149 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001150 }
1151
John McCall9f3059a2009-10-09 21:13:30 +00001152 R.resolveKind();
1153
1154 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001155 }
Douglas Gregor34074322009-01-14 22:20:51 +00001156 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001157 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001158 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001159 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001160 }
1161
1162 // If we didn't find a use of this identifier, and if the identifier
1163 // corresponds to a compiler builtin, create the decl object for the builtin
1164 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001165 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1166 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001167
Axel Naumann016538a2011-02-24 16:47:47 +00001168 // If we didn't find a use of this identifier, the ExternalSource
1169 // may be able to handle the situation.
1170 // Note: some lookup failures are expected!
1171 // See e.g. R.isForRedeclaration().
1172 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001173}
1174
John McCall6538c932009-10-10 05:48:19 +00001175/// @brief Perform qualified name lookup in the namespaces nominated by
1176/// using directives by the given context.
1177///
1178/// C++98 [namespace.qual]p2:
1179/// Given X::m (where X is a user-declared namespace), or given ::m
1180/// (where X is the global namespace), let S be the set of all
1181/// declarations of m in X and in the transitive closure of all
1182/// namespaces nominated by using-directives in X and its used
1183/// namespaces, except that using-directives are ignored in any
1184/// namespace, including X, directly containing one or more
1185/// declarations of m. No namespace is searched more than once in
1186/// the lookup of a name. If S is the empty set, the program is
1187/// ill-formed. Otherwise, if S has exactly one member, or if the
1188/// context of the reference is a using-declaration
1189/// (namespace.udecl), S is the required set of declarations of
1190/// m. Otherwise if the use of m is not one that allows a unique
1191/// declaration to be chosen from S, the program is ill-formed.
1192/// C++98 [namespace.qual]p5:
1193/// During the lookup of a qualified namespace member name, if the
1194/// lookup finds more than one declaration of the member, and if one
1195/// declaration introduces a class name or enumeration name and the
1196/// other declarations either introduce the same object, the same
1197/// enumerator or a set of functions, the non-type name hides the
1198/// class or enumeration name if and only if the declarations are
1199/// from the same namespace; otherwise (the declarations are from
1200/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001201static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001202 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001203 assert(StartDC->isFileContext() && "start context is not a file context");
1204
1205 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1206 DeclContext::udir_iterator E = StartDC->using_directives_end();
1207
1208 if (I == E) return false;
1209
1210 // We have at least added all these contexts to the queue.
1211 llvm::DenseSet<DeclContext*> Visited;
1212 Visited.insert(StartDC);
1213
1214 // We have not yet looked into these namespaces, much less added
1215 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001216 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001217
1218 // We have already looked into the initial namespace; seed the queue
1219 // with its using-children.
1220 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001221 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001222 if (Visited.insert(ND).second)
1223 Queue.push_back(ND);
1224 }
1225
1226 // The easiest way to implement the restriction in [namespace.qual]p5
1227 // is to check whether any of the individual results found a tag
1228 // and, if so, to declare an ambiguity if the final result is not
1229 // a tag.
1230 bool FoundTag = false;
1231 bool FoundNonTag = false;
1232
John McCall5cebab12009-11-18 07:57:50 +00001233 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001234
1235 bool Found = false;
1236 while (!Queue.empty()) {
1237 NamespaceDecl *ND = Queue.back();
1238 Queue.pop_back();
1239
1240 // We go through some convolutions here to avoid copying results
1241 // between LookupResults.
1242 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001243 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001244 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001245
1246 if (FoundDirect) {
1247 // First do any local hiding.
1248 DirectR.resolveKind();
1249
1250 // If the local result is a tag, remember that.
1251 if (DirectR.isSingleTagDecl())
1252 FoundTag = true;
1253 else
1254 FoundNonTag = true;
1255
1256 // Append the local results to the total results if necessary.
1257 if (UseLocal) {
1258 R.addAllDecls(LocalR);
1259 LocalR.clear();
1260 }
1261 }
1262
1263 // If we find names in this namespace, ignore its using directives.
1264 if (FoundDirect) {
1265 Found = true;
1266 continue;
1267 }
1268
1269 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1270 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1271 if (Visited.insert(Nom).second)
1272 Queue.push_back(Nom);
1273 }
1274 }
1275
1276 if (Found) {
1277 if (FoundTag && FoundNonTag)
1278 R.setAmbiguousQualifiedTagHiding();
1279 else
1280 R.resolveKind();
1281 }
1282
1283 return Found;
1284}
1285
Douglas Gregor39982192010-08-15 06:18:01 +00001286/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001288 CXXBasePath &Path,
1289 void *Name) {
1290 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001291
Douglas Gregor39982192010-08-15 06:18:01 +00001292 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1293 Path.Decls = BaseRecord->lookup(N);
1294 return Path.Decls.first != Path.Decls.second;
1295}
1296
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001298/// static members, nested types, and enumerators.
1299template<typename InputIterator>
1300static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1301 Decl *D = (*First)->getUnderlyingDecl();
1302 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1303 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304
Douglas Gregorc0d24902010-10-22 22:08:47 +00001305 if (isa<CXXMethodDecl>(D)) {
1306 // Determine whether all of the methods are static.
1307 bool AllMethodsAreStatic = true;
1308 for(; First != Last; ++First) {
1309 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310
Douglas Gregorc0d24902010-10-22 22:08:47 +00001311 if (!isa<CXXMethodDecl>(D)) {
1312 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1313 break;
1314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001315
Douglas Gregorc0d24902010-10-22 22:08:47 +00001316 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1317 AllMethodsAreStatic = false;
1318 break;
1319 }
1320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321
Douglas Gregorc0d24902010-10-22 22:08:47 +00001322 if (AllMethodsAreStatic)
1323 return true;
1324 }
1325
1326 return false;
1327}
1328
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001329/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001330///
1331/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1332/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001333/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001334///
1335/// Different lookup criteria can find different names. For example, a
1336/// particular scope can have both a struct and a function of the same
1337/// name, and each can be found by certain lookup criteria. For more
1338/// information about lookup criteria, see the documentation for the
1339/// class LookupCriteria.
1340///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001341/// \param R captures both the lookup criteria and any lookup results found.
1342///
1343/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001344/// search. If the lookup criteria permits, name lookup may also search
1345/// in the parent contexts or (for C++ classes) base classes.
1346///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001348/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001349///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001350/// \returns true if lookup succeeded, false if it failed.
1351bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1352 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001353 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001354
John McCall27b18f82009-11-17 02:14:36 +00001355 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001356 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001357
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001358 // Make sure that the declaration context is complete.
1359 assert((!isa<TagDecl>(LookupCtx) ||
1360 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001361 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001362 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1363 ->isBeingDefined()) &&
1364 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001365
Douglas Gregor34074322009-01-14 22:20:51 +00001366 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001367 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001368 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001369 if (isa<CXXRecordDecl>(LookupCtx))
1370 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001371 return true;
1372 }
Douglas Gregor34074322009-01-14 22:20:51 +00001373
John McCall6538c932009-10-10 05:48:19 +00001374 // Don't descend into implied contexts for redeclarations.
1375 // C++98 [namespace.qual]p6:
1376 // In a declaration for a namespace member in which the
1377 // declarator-id is a qualified-id, given that the qualified-id
1378 // for the namespace member has the form
1379 // nested-name-specifier unqualified-id
1380 // the unqualified-id shall name a member of the namespace
1381 // designated by the nested-name-specifier.
1382 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001383 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001384 return false;
1385
John McCall27b18f82009-11-17 02:14:36 +00001386 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001387 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001388 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001389
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001390 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001391 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001392 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001393 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001394 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001395
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001396 // If we're performing qualified name lookup into a dependent class,
1397 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001398 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001399 // template instantiation time (at which point all bases will be available)
1400 // or we have to fail.
1401 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1402 LookupRec->hasAnyDependentBases()) {
1403 R.setNotFoundInCurrentInstantiation();
1404 return false;
1405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001406
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001407 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001408 CXXBasePaths Paths;
1409 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001410
1411 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001412 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001413 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001414 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001415 case LookupOrdinaryName:
1416 case LookupMemberName:
1417 case LookupRedeclarationWithLinkage:
1418 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1419 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001420
Douglas Gregor36d1b142009-10-06 17:59:45 +00001421 case LookupTagName:
1422 BaseCallback = &CXXRecordDecl::FindTagMember;
1423 break;
John McCall84d87672009-12-10 09:41:52 +00001424
Douglas Gregor39982192010-08-15 06:18:01 +00001425 case LookupAnyName:
1426 BaseCallback = &LookupAnyMember;
1427 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001428
John McCall84d87672009-12-10 09:41:52 +00001429 case LookupUsingDeclName:
1430 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001431
Douglas Gregor36d1b142009-10-06 17:59:45 +00001432 case LookupOperatorName:
1433 case LookupNamespaceName:
1434 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001435 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001436 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001437 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001438
Douglas Gregor36d1b142009-10-06 17:59:45 +00001439 case LookupNestedNameSpecifierName:
1440 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1441 break;
1442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001443
John McCall27b18f82009-11-17 02:14:36 +00001444 if (!LookupRec->lookupInBases(BaseCallback,
1445 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001446 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001447
John McCall553c0792010-01-23 00:46:32 +00001448 R.setNamingClass(LookupRec);
1449
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001450 // C++ [class.member.lookup]p2:
1451 // [...] If the resulting set of declarations are not all from
1452 // sub-objects of the same type, or the set has a nonstatic member
1453 // and includes members from distinct sub-objects, there is an
1454 // ambiguity and the program is ill-formed. Otherwise that set is
1455 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001456 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001457 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001458 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459
Douglas Gregor36d1b142009-10-06 17:59:45 +00001460 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001461 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001462 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001463
John McCall401982f2010-01-20 21:53:11 +00001464 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1465 // across all paths.
1466 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001468 // Determine whether we're looking at a distinct sub-object or not.
1469 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001470 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001471 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1472 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001473 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001474 }
1475
Douglas Gregorc0d24902010-10-22 22:08:47 +00001476 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001477 != Context.getCanonicalType(PathElement.Base->getType())) {
1478 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001479 // different types. If the declaration sets aren't the same, this
1480 // this lookup is ambiguous.
1481 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1482 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1483 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1484 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
Douglas Gregorc0d24902010-10-22 22:08:47 +00001486 while (FirstD != FirstPath->Decls.second &&
1487 CurrentD != Path->Decls.second) {
1488 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1489 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1490 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001491
Douglas Gregorc0d24902010-10-22 22:08:47 +00001492 ++FirstD;
1493 ++CurrentD;
1494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
Douglas Gregorc0d24902010-10-22 22:08:47 +00001496 if (FirstD == FirstPath->Decls.second &&
1497 CurrentD == Path->Decls.second)
1498 continue;
1499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001500
John McCall9f3059a2009-10-09 21:13:30 +00001501 R.setAmbiguousBaseSubobjectTypes(Paths);
1502 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001503 }
1504
Douglas Gregorc0d24902010-10-22 22:08:47 +00001505 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001506 // We have a different subobject of the same type.
1507
1508 // C++ [class.member.lookup]p5:
1509 // A static member, a nested type or an enumerator defined in
1510 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001511 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001512 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001513 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001514
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001515 // We have found a nonstatic member name in multiple, distinct
1516 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001517 R.setAmbiguousBaseSubobjects(Paths);
1518 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001519 }
1520 }
1521
1522 // Lookup in a base class succeeded; return these results.
1523
John McCall9f3059a2009-10-09 21:13:30 +00001524 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001525 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1526 NamedDecl *D = *I;
1527 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1528 D->getAccess());
1529 R.addDecl(D, AS);
1530 }
John McCall9f3059a2009-10-09 21:13:30 +00001531 R.resolveKind();
1532 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001533}
1534
1535/// @brief Performs name lookup for a name that was parsed in the
1536/// source code, and may contain a C++ scope specifier.
1537///
1538/// This routine is a convenience routine meant to be called from
1539/// contexts that receive a name and an optional C++ scope specifier
1540/// (e.g., "N::M::x"). It will then perform either qualified or
1541/// unqualified name lookup (with LookupQualifiedName or LookupName,
1542/// respectively) on the given name and return those results.
1543///
1544/// @param S The scope from which unqualified name lookup will
1545/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001546///
Douglas Gregore861bac2009-08-25 22:51:20 +00001547/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001548///
Douglas Gregore861bac2009-08-25 22:51:20 +00001549/// @param EnteringContext Indicates whether we are going to enter the
1550/// context of the scope-specifier SS (if present).
1551///
John McCall9f3059a2009-10-09 21:13:30 +00001552/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001553bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001554 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001555 if (SS && SS->isInvalid()) {
1556 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001557 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001558 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001559 }
Mike Stump11289f42009-09-09 15:08:12 +00001560
Douglas Gregore861bac2009-08-25 22:51:20 +00001561 if (SS && SS->isSet()) {
1562 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001563 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001564 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001565 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001566 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001567
John McCall27b18f82009-11-17 02:14:36 +00001568 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001569 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001570 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001571
Douglas Gregore861bac2009-08-25 22:51:20 +00001572 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001573 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001574 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001575 R.setNotFoundInCurrentInstantiation();
1576 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001577 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001578 }
1579
Mike Stump11289f42009-09-09 15:08:12 +00001580 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001581 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001582}
1583
Douglas Gregor889ceb72009-02-03 19:21:40 +00001584
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001585/// @brief Produce a diagnostic describing the ambiguity that resulted
1586/// from name lookup.
1587///
1588/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001589///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001590/// @param Name The name of the entity that name lookup was
1591/// searching for.
1592///
1593/// @param NameLoc The location of the name within the source code.
1594///
1595/// @param LookupRange A source range that provides more
1596/// source-location information concerning the lookup itself. For
1597/// example, this range might highlight a nested-name-specifier that
1598/// precedes the name.
1599///
1600/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001601bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001602 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1603
John McCall27b18f82009-11-17 02:14:36 +00001604 DeclarationName Name = Result.getLookupName();
1605 SourceLocation NameLoc = Result.getNameLoc();
1606 SourceRange LookupRange = Result.getContextRange();
1607
John McCall6538c932009-10-10 05:48:19 +00001608 switch (Result.getAmbiguityKind()) {
1609 case LookupResult::AmbiguousBaseSubobjects: {
1610 CXXBasePaths *Paths = Result.getBasePaths();
1611 QualType SubobjectType = Paths->front().back().Base->getType();
1612 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1613 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1614 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615
John McCall6538c932009-10-10 05:48:19 +00001616 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1617 while (isa<CXXMethodDecl>(*Found) &&
1618 cast<CXXMethodDecl>(*Found)->isStatic())
1619 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001620
John McCall6538c932009-10-10 05:48:19 +00001621 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001622
John McCall6538c932009-10-10 05:48:19 +00001623 return true;
1624 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001625
John McCall6538c932009-10-10 05:48:19 +00001626 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001627 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1628 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001629
John McCall6538c932009-10-10 05:48:19 +00001630 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001631 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001632 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1633 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001634 Path != PathEnd; ++Path) {
1635 Decl *D = *Path->Decls.first;
1636 if (DeclsPrinted.insert(D).second)
1637 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1638 }
1639
Douglas Gregor1c846b02009-01-16 00:38:09 +00001640 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001641 }
1642
John McCall6538c932009-10-10 05:48:19 +00001643 case LookupResult::AmbiguousTagHiding: {
1644 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001645
John McCall6538c932009-10-10 05:48:19 +00001646 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1647
1648 LookupResult::iterator DI, DE = Result.end();
1649 for (DI = Result.begin(); DI != DE; ++DI)
1650 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1651 TagDecls.insert(TD);
1652 Diag(TD->getLocation(), diag::note_hidden_tag);
1653 }
1654
1655 for (DI = Result.begin(); DI != DE; ++DI)
1656 if (!isa<TagDecl>(*DI))
1657 Diag((*DI)->getLocation(), diag::note_hiding_object);
1658
1659 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001660 LookupResult::Filter F = Result.makeFilter();
1661 while (F.hasNext()) {
1662 if (TagDecls.count(F.next()))
1663 F.erase();
1664 }
1665 F.done();
John McCall6538c932009-10-10 05:48:19 +00001666
1667 return true;
1668 }
1669
1670 case LookupResult::AmbiguousReference: {
1671 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001672
John McCall6538c932009-10-10 05:48:19 +00001673 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1674 for (; DI != DE; ++DI)
1675 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001676
John McCall6538c932009-10-10 05:48:19 +00001677 return true;
1678 }
1679 }
1680
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001681 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001682 return true;
1683}
Douglas Gregore254f902009-02-04 00:32:51 +00001684
John McCallf24d7bb2010-05-28 18:45:08 +00001685namespace {
1686 struct AssociatedLookup {
1687 AssociatedLookup(Sema &S,
1688 Sema::AssociatedNamespaceSet &Namespaces,
1689 Sema::AssociatedClassSet &Classes)
1690 : S(S), Namespaces(Namespaces), Classes(Classes) {
1691 }
1692
1693 Sema &S;
1694 Sema::AssociatedNamespaceSet &Namespaces;
1695 Sema::AssociatedClassSet &Classes;
1696 };
1697}
1698
Mike Stump11289f42009-09-09 15:08:12 +00001699static void
John McCallf24d7bb2010-05-28 18:45:08 +00001700addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001701
Douglas Gregor8b895222010-04-30 07:08:38 +00001702static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1703 DeclContext *Ctx) {
1704 // Add the associated namespace for this class.
1705
1706 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1707 // be a locally scoped record.
1708
Sebastian Redlbd595762010-08-31 20:53:31 +00001709 // We skip out of inline namespaces. The innermost non-inline namespace
1710 // contains all names of all its nested inline namespaces anyway, so we can
1711 // replace the entire inline namespace tree with its root.
1712 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1713 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001714 Ctx = Ctx->getParent();
1715
John McCallc7e8e792009-08-07 22:18:02 +00001716 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001717 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001718}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001719
Mike Stump11289f42009-09-09 15:08:12 +00001720// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001721// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001722static void
John McCallf24d7bb2010-05-28 18:45:08 +00001723addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1724 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001725 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001726 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001727 switch (Arg.getKind()) {
1728 case TemplateArgument::Null:
1729 break;
Mike Stump11289f42009-09-09 15:08:12 +00001730
Douglas Gregor197e5f72009-07-08 07:51:57 +00001731 case TemplateArgument::Type:
1732 // [...] the namespaces and classes associated with the types of the
1733 // template arguments provided for template type parameters (excluding
1734 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001735 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001736 break;
Mike Stump11289f42009-09-09 15:08:12 +00001737
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001739 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001740 // [...] the namespaces in which any template template arguments are
1741 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001742 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001743 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001744 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001745 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001746 DeclContext *Ctx = ClassTemplate->getDeclContext();
1747 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001748 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001749 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001750 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001751 }
1752 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001754
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001755 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001756 case TemplateArgument::Integral:
1757 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001758 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001759 // associated namespaces. ]
1760 break;
Mike Stump11289f42009-09-09 15:08:12 +00001761
Douglas Gregor197e5f72009-07-08 07:51:57 +00001762 case TemplateArgument::Pack:
1763 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1764 PEnd = Arg.pack_end();
1765 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001766 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001767 break;
1768 }
1769}
1770
Douglas Gregore254f902009-02-04 00:32:51 +00001771// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001772// argument-dependent lookup with an argument of class type
1773// (C++ [basic.lookup.koenig]p2).
1774static void
John McCallf24d7bb2010-05-28 18:45:08 +00001775addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1776 CXXRecordDecl *Class) {
1777
1778 // Just silently ignore anything whose name is __va_list_tag.
1779 if (Class->getDeclName() == Result.S.VAListTagName)
1780 return;
1781
Douglas Gregore254f902009-02-04 00:32:51 +00001782 // C++ [basic.lookup.koenig]p2:
1783 // [...]
1784 // -- If T is a class type (including unions), its associated
1785 // classes are: the class itself; the class of which it is a
1786 // member, if any; and its direct and indirect base
1787 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001788 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001789
1790 // Add the class of which it is a member, if any.
1791 DeclContext *Ctx = Class->getDeclContext();
1792 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001793 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001794 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001795 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001796
Douglas Gregore254f902009-02-04 00:32:51 +00001797 // Add the class itself. If we've already seen this class, we don't
1798 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001799 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001800 return;
1801
Mike Stump11289f42009-09-09 15:08:12 +00001802 // -- If T is a template-id, its associated namespaces and classes are
1803 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001804 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001805 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001806 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001807 // namespaces in which any template template arguments are defined; and
1808 // the classes in which any member templates used as template template
1809 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001810 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001811 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001812 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1813 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1814 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001815 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001816 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001817 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001818
Douglas Gregor197e5f72009-07-08 07:51:57 +00001819 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1820 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001821 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001822 }
Mike Stump11289f42009-09-09 15:08:12 +00001823
John McCall67da35c2010-02-04 22:26:26 +00001824 // Only recurse into base classes for complete types.
1825 if (!Class->hasDefinition()) {
1826 // FIXME: we might need to instantiate templates here
1827 return;
1828 }
1829
Douglas Gregore254f902009-02-04 00:32:51 +00001830 // Add direct and indirect base classes along with their associated
1831 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001832 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00001833 Bases.push_back(Class);
1834 while (!Bases.empty()) {
1835 // Pop this class off the stack.
1836 Class = Bases.back();
1837 Bases.pop_back();
1838
1839 // Visit the base classes.
1840 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1841 BaseEnd = Class->bases_end();
1842 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001843 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001844 // In dependent contexts, we do ADL twice, and the first time around,
1845 // the base type might be a dependent TemplateSpecializationType, or a
1846 // TemplateTypeParmType. If that happens, simply ignore it.
1847 // FIXME: If we want to support export, we probably need to add the
1848 // namespace of the template in a TemplateSpecializationType, or even
1849 // the classes and namespaces of known non-dependent arguments.
1850 if (!BaseType)
1851 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001852 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001853 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001854 // Find the associated namespace for this base class.
1855 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001856 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001857
1858 // Make sure we visit the bases of this base class.
1859 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1860 Bases.push_back(BaseDecl);
1861 }
1862 }
1863 }
1864}
1865
1866// \brief Add the associated classes and namespaces for
1867// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001868// (C++ [basic.lookup.koenig]p2).
1869static void
John McCallf24d7bb2010-05-28 18:45:08 +00001870addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001871 // C++ [basic.lookup.koenig]p2:
1872 //
1873 // For each argument type T in the function call, there is a set
1874 // of zero or more associated namespaces and a set of zero or more
1875 // associated classes to be considered. The sets of namespaces and
1876 // classes is determined entirely by the types of the function
1877 // arguments (and the namespace of any template template
1878 // argument). Typedef names and using-declarations used to specify
1879 // the types do not contribute to this set. The sets of namespaces
1880 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001881
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001882 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00001883 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1884
Douglas Gregore254f902009-02-04 00:32:51 +00001885 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001886 switch (T->getTypeClass()) {
1887
1888#define TYPE(Class, Base)
1889#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1890#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1891#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1892#define ABSTRACT_TYPE(Class, Base)
1893#include "clang/AST/TypeNodes.def"
1894 // T is canonical. We can also ignore dependent types because
1895 // we don't need to do ADL at the definition point, but if we
1896 // wanted to implement template export (or if we find some other
1897 // use for associated classes and namespaces...) this would be
1898 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001899 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001900
John McCall0af3d3b2010-05-28 06:08:54 +00001901 // -- If T is a pointer to U or an array of U, its associated
1902 // namespaces and classes are those associated with U.
1903 case Type::Pointer:
1904 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1905 continue;
1906 case Type::ConstantArray:
1907 case Type::IncompleteArray:
1908 case Type::VariableArray:
1909 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1910 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001911
John McCall0af3d3b2010-05-28 06:08:54 +00001912 // -- If T is a fundamental type, its associated sets of
1913 // namespaces and classes are both empty.
1914 case Type::Builtin:
1915 break;
1916
1917 // -- If T is a class type (including unions), its associated
1918 // classes are: the class itself; the class of which it is a
1919 // member, if any; and its direct and indirect base
1920 // classes. Its associated namespaces are the namespaces in
1921 // which its associated classes are defined.
1922 case Type::Record: {
1923 CXXRecordDecl *Class
1924 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001925 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001926 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001927 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001928
John McCall0af3d3b2010-05-28 06:08:54 +00001929 // -- If T is an enumeration type, its associated namespace is
1930 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001931 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001932 // it has no associated class.
1933 case Type::Enum: {
1934 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001935
John McCall0af3d3b2010-05-28 06:08:54 +00001936 DeclContext *Ctx = Enum->getDeclContext();
1937 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001938 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001939
John McCall0af3d3b2010-05-28 06:08:54 +00001940 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001941 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001942
John McCall0af3d3b2010-05-28 06:08:54 +00001943 break;
1944 }
1945
1946 // -- If T is a function type, its associated namespaces and
1947 // classes are those associated with the function parameter
1948 // types and those associated with the return type.
1949 case Type::FunctionProto: {
1950 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1951 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1952 ArgEnd = Proto->arg_type_end();
1953 Arg != ArgEnd; ++Arg)
1954 Queue.push_back(Arg->getTypePtr());
1955 // fallthrough
1956 }
1957 case Type::FunctionNoProto: {
1958 const FunctionType *FnType = cast<FunctionType>(T);
1959 T = FnType->getResultType().getTypePtr();
1960 continue;
1961 }
1962
1963 // -- If T is a pointer to a member function of a class X, its
1964 // associated namespaces and classes are those associated
1965 // with the function parameter types and return type,
1966 // together with those associated with X.
1967 //
1968 // -- If T is a pointer to a data member of class X, its
1969 // associated namespaces and classes are those associated
1970 // with the member type together with those associated with
1971 // X.
1972 case Type::MemberPointer: {
1973 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1974
1975 // Queue up the class type into which this points.
1976 Queue.push_back(MemberPtr->getClass());
1977
1978 // And directly continue with the pointee type.
1979 T = MemberPtr->getPointeeType().getTypePtr();
1980 continue;
1981 }
1982
1983 // As an extension, treat this like a normal pointer.
1984 case Type::BlockPointer:
1985 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1986 continue;
1987
1988 // References aren't covered by the standard, but that's such an
1989 // obvious defect that we cover them anyway.
1990 case Type::LValueReference:
1991 case Type::RValueReference:
1992 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1993 continue;
1994
1995 // These are fundamental types.
1996 case Type::Vector:
1997 case Type::ExtVector:
1998 case Type::Complex:
1999 break;
2000
Douglas Gregor8e936662011-04-12 01:02:45 +00002001 // If T is an Objective-C object or interface type, or a pointer to an
2002 // object or interface type, the associated namespace is the global
2003 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002004 case Type::ObjCObject:
2005 case Type::ObjCInterface:
2006 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002007 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002008 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002009
2010 // Atomic types are just wrappers; use the associations of the
2011 // contained type.
2012 case Type::Atomic:
2013 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2014 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002015 }
2016
2017 if (Queue.empty()) break;
2018 T = Queue.back();
2019 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00002020 }
Douglas Gregore254f902009-02-04 00:32:51 +00002021}
2022
2023/// \brief Find the associated classes and namespaces for
2024/// argument-dependent lookup for a call with the given set of
2025/// arguments.
2026///
2027/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002028/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002029/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002030void
Douglas Gregore254f902009-02-04 00:32:51 +00002031Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2032 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002033 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002034 AssociatedNamespaces.clear();
2035 AssociatedClasses.clear();
2036
John McCallf24d7bb2010-05-28 18:45:08 +00002037 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2038
Douglas Gregore254f902009-02-04 00:32:51 +00002039 // C++ [basic.lookup.koenig]p2:
2040 // For each argument type T in the function call, there is a set
2041 // of zero or more associated namespaces and a set of zero or more
2042 // associated classes to be considered. The sets of namespaces and
2043 // classes is determined entirely by the types of the function
2044 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002045 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00002046 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2047 Expr *Arg = Args[ArgIdx];
2048
2049 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002050 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002051 continue;
2052 }
2053
2054 // [...] In addition, if the argument is the name or address of a
2055 // set of overloaded functions and/or function templates, its
2056 // associated classes and namespaces are the union of those
2057 // associated with each of the members of the set: the namespace
2058 // in which the function or function template is defined and the
2059 // classes and namespaces associated with its (non-dependent)
2060 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002061 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002062 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002063 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002064 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002065
John McCallf24d7bb2010-05-28 18:45:08 +00002066 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2067 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002068
John McCallf24d7bb2010-05-28 18:45:08 +00002069 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2070 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002071 // Look through any using declarations to find the underlying function.
2072 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002073
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002074 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2075 if (!FDecl)
2076 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002077
2078 // Add the classes and namespaces associated with the parameter
2079 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002080 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002081 }
2082 }
2083}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002084
2085/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2086/// an acceptable non-member overloaded operator for a call whose
2087/// arguments have types T1 (and, if non-empty, T2). This routine
2088/// implements the check in C++ [over.match.oper]p3b2 concerning
2089/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002090static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002091IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2092 QualType T1, QualType T2,
2093 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002094 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2095 return true;
2096
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002097 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2098 return true;
2099
John McCall9dd450b2009-09-21 23:43:11 +00002100 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002101 if (Proto->getNumArgs() < 1)
2102 return false;
2103
2104 if (T1->isEnumeralType()) {
2105 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002106 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002107 return true;
2108 }
2109
2110 if (Proto->getNumArgs() < 2)
2111 return false;
2112
2113 if (!T2.isNull() && T2->isEnumeralType()) {
2114 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002115 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002116 return true;
2117 }
2118
2119 return false;
2120}
2121
John McCall5cebab12009-11-18 07:57:50 +00002122NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002123 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002124 LookupNameKind NameKind,
2125 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002126 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002127 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002128 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002129}
2130
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002131/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002132ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002133 SourceLocation IdLoc) {
2134 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2135 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002136 return cast_or_null<ObjCProtocolDecl>(D);
2137}
2138
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002139void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002140 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002141 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002142 // C++ [over.match.oper]p3:
2143 // -- The set of non-member candidates is the result of the
2144 // unqualified lookup of operator@ in the context of the
2145 // expression according to the usual rules for name lookup in
2146 // unqualified function calls (3.4.2) except that all member
2147 // functions are ignored. However, if no operand has a class
2148 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002149 // that have a first parameter of type T1 or "reference to
2150 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002151 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002152 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002153 // when T2 is an enumeration type, are candidate functions.
2154 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002155 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2156 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002157
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002158 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2159
John McCall9f3059a2009-10-09 21:13:30 +00002160 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002161 return;
2162
2163 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2164 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002165 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2166 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002167 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002168 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002169 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002170 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002171 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002172 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002173 // later?
2174 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002175 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002176 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002177 }
2178}
2179
Alexis Hunt1da39282011-06-24 02:11:39 +00002180Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002181 CXXSpecialMember SM,
2182 bool ConstArg,
2183 bool VolatileArg,
2184 bool RValueThis,
2185 bool ConstThis,
2186 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002187 RD = RD->getDefinition();
2188 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002189 "doing special member lookup into record that isn't fully complete");
2190 if (RValueThis || ConstThis || VolatileThis)
2191 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2192 "constructors and destructors always have unqualified lvalue this");
2193 if (ConstArg || VolatileArg)
2194 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2195 "parameter-less special members can't have qualified arguments");
2196
2197 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002198 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002199 ID.AddInteger(SM);
2200 ID.AddInteger(ConstArg);
2201 ID.AddInteger(VolatileArg);
2202 ID.AddInteger(RValueThis);
2203 ID.AddInteger(ConstThis);
2204 ID.AddInteger(VolatileThis);
2205
2206 void *InsertPoint;
2207 SpecialMemberOverloadResult *Result =
2208 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2209
2210 // This was already cached
2211 if (Result)
2212 return Result;
2213
Alexis Huntba8e18d2011-06-07 00:11:58 +00002214 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2215 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002216 SpecialMemberCache.InsertNode(Result, InsertPoint);
2217
2218 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002219 if (!RD->hasDeclaredDestructor())
2220 DeclareImplicitDestructor(RD);
2221 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002222 assert(DD && "record without a destructor");
2223 Result->setMethod(DD);
2224 Result->setSuccess(DD->isDeleted());
2225 Result->setConstParamMatch(false);
2226 return Result;
2227 }
2228
Alexis Hunteef8ee02011-06-10 03:50:41 +00002229 // Prepare for overload resolution. Here we construct a synthetic argument
2230 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002231 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002232 DeclarationName Name;
2233 Expr *Arg = 0;
2234 unsigned NumArgs;
2235
2236 if (SM == CXXDefaultConstructor) {
2237 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2238 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002239 if (RD->needsImplicitDefaultConstructor())
2240 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002241 } else {
2242 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2243 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002244 if (!RD->hasDeclaredCopyConstructor())
2245 DeclareImplicitCopyConstructor(RD);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002246 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2247 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002248 } else {
2249 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002250 if (!RD->hasDeclaredCopyAssignment())
2251 DeclareImplicitCopyAssignment(RD);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002252 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2253 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002254 }
2255
2256 QualType ArgType = CanTy;
2257 if (ConstArg)
2258 ArgType.addConst();
2259 if (VolatileArg)
2260 ArgType.addVolatile();
2261
2262 // This isn't /really/ specified by the standard, but it's implied
2263 // we should be working from an RValue in the case of move to ensure
2264 // that we prefer to bind to rvalue references, and an LValue in the
2265 // case of copy to ensure we don't bind to rvalue references.
2266 // Possibly an XValue is actually correct in the case of move, but
2267 // there is no semantic difference for class types in this restricted
2268 // case.
2269 ExprValueKind VK;
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002270 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002271 VK = VK_LValue;
2272 else
2273 VK = VK_RValue;
2274
2275 NumArgs = 1;
2276 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2277 }
2278
2279 // Create the object argument
2280 QualType ThisTy = CanTy;
2281 if (ConstThis)
2282 ThisTy.addConst();
2283 if (VolatileThis)
2284 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002285 Expr::Classification Classification =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002286 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2287 RValueThis ? VK_RValue : VK_LValue))->
2288 Classify(Context);
2289
2290 // Now we perform lookup on the name we computed earlier and do overload
2291 // resolution. Lookup is only performed directly into the class since there
2292 // will always be a (possibly implicit) declaration to shadow any others.
2293 OverloadCandidateSet OCS((SourceLocation()));
2294 DeclContext::lookup_iterator I, E;
2295 Result->setConstParamMatch(false);
2296
Alexis Hunt1da39282011-06-24 02:11:39 +00002297 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002298 assert((I != E) &&
2299 "lookup for a constructor or assignment operator was empty");
2300 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002301 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002302
Alexis Hunt1da39282011-06-24 02:11:39 +00002303 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002304 continue;
2305
Alexis Hunt1da39282011-06-24 02:11:39 +00002306 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2307 // FIXME: [namespace.udecl]p15 says that we should only consider a
2308 // using declaration here if it does not match a declaration in the
2309 // derived class. We do not implement this correctly in other cases
2310 // either.
2311 Cand = U->getTargetDecl();
2312
2313 if (Cand->isInvalidDecl())
2314 continue;
2315 }
2316
2317 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002318 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002319 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Alexis Hunt080709f2011-06-23 00:26:20 +00002320 Classification, &Arg, NumArgs, OCS, true);
2321 else
2322 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2323 NumArgs, OCS, true);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002324
2325 // Here we're looking for a const parameter to speed up creation of
2326 // implicit copy methods.
2327 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2328 (SM == CXXCopyConstructor &&
2329 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2330 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Alexis Hunt491ec602011-06-21 23:42:56 +00002331 if (!ArgType->isReferenceType() ||
2332 ArgType->getPointeeType().isConstQualified())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002333 Result->setConstParamMatch(true);
2334 }
Alexis Hunt2949f022011-06-22 02:58:46 +00002335 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002336 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002337 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2338 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Alexis Hunt1da39282011-06-24 02:11:39 +00002339 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Alexis Hunt080709f2011-06-23 00:26:20 +00002340 OCS, true);
2341 else
2342 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2343 0, &Arg, NumArgs, OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002344 } else {
2345 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002346 }
2347 }
2348
2349 OverloadCandidateSet::iterator Best;
2350 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2351 case OR_Success:
2352 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2353 Result->setSuccess(true);
2354 break;
2355
2356 case OR_Deleted:
2357 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2358 Result->setSuccess(false);
2359 break;
2360
2361 case OR_Ambiguous:
2362 case OR_No_Viable_Function:
2363 Result->setMethod(0);
2364 Result->setSuccess(false);
2365 break;
2366 }
2367
2368 return Result;
2369}
2370
2371/// \brief Look up the default constructor for the given class.
2372CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002373 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002374 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2375 false, false);
2376
2377 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002378}
2379
Alexis Hunt491ec602011-06-21 23:42:56 +00002380/// \brief Look up the copying constructor for the given class.
2381CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2382 unsigned Quals,
2383 bool *ConstParamMatch) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002384 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2385 "non-const, non-volatile qualifiers for copy ctor arg");
2386 SpecialMemberOverloadResult *Result =
2387 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2388 Quals & Qualifiers::Volatile, false, false, false);
2389
2390 if (ConstParamMatch)
2391 *ConstParamMatch = Result->hasConstParamMatch();
2392
2393 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2394}
2395
Sebastian Redl22653ba2011-08-30 19:58:05 +00002396/// \brief Look up the moving constructor for the given class.
2397CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2398 SpecialMemberOverloadResult *Result =
2399 LookupSpecialMember(Class, CXXMoveConstructor, false,
2400 false, false, false, false);
2401
2402 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2403}
2404
Douglas Gregor52b72822010-07-02 23:12:18 +00002405/// \brief Look up the constructors for the given class.
2406DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002407 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002408 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002409 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002410 DeclareImplicitDefaultConstructor(Class);
2411 if (!Class->hasDeclaredCopyConstructor())
2412 DeclareImplicitCopyConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002413 if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2414 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002416
Douglas Gregor52b72822010-07-02 23:12:18 +00002417 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2418 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2419 return Class->lookup(Name);
2420}
2421
Alexis Hunt491ec602011-06-21 23:42:56 +00002422/// \brief Look up the copying assignment operator for the given class.
2423CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2424 unsigned Quals, bool RValueThis,
2425 unsigned ThisQuals,
2426 bool *ConstParamMatch) {
2427 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2428 "non-const, non-volatile qualifiers for copy assignment arg");
2429 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2430 "non-const, non-volatile qualifiers for copy assignment this");
2431 SpecialMemberOverloadResult *Result =
2432 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2433 Quals & Qualifiers::Volatile, RValueThis,
2434 ThisQuals & Qualifiers::Const,
2435 ThisQuals & Qualifiers::Volatile);
2436
2437 if (ConstParamMatch)
2438 *ConstParamMatch = Result->hasConstParamMatch();
2439
2440 return Result->getMethod();
2441}
2442
Sebastian Redl22653ba2011-08-30 19:58:05 +00002443/// \brief Look up the moving assignment operator for the given class.
2444CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2445 bool RValueThis,
2446 unsigned ThisQuals) {
2447 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2448 "non-const, non-volatile qualifiers for copy assignment this");
2449 SpecialMemberOverloadResult *Result =
2450 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2451 ThisQuals & Qualifiers::Const,
2452 ThisQuals & Qualifiers::Volatile);
2453
2454 return Result->getMethod();
2455}
2456
Douglas Gregore71edda2010-07-01 22:47:18 +00002457/// \brief Look for the destructor of the given class.
2458///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002459/// During semantic analysis, this routine should be used in lieu of
2460/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002461///
2462/// \returns The destructor for this class.
2463CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002464 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2465 false, false, false,
2466 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002467}
2468
John McCall8fe68082010-01-26 07:16:45 +00002469void ADLResult::insert(NamedDecl *New) {
2470 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2471
2472 // If we haven't yet seen a decl for this key, or the last decl
2473 // was exactly this one, we're done.
2474 if (Old == 0 || Old == New) {
2475 Old = New;
2476 return;
2477 }
2478
2479 // Otherwise, decide which is a more recent redeclaration.
2480 FunctionDecl *OldFD, *NewFD;
2481 if (isa<FunctionTemplateDecl>(New)) {
2482 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2483 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2484 } else {
2485 OldFD = cast<FunctionDecl>(Old);
2486 NewFD = cast<FunctionDecl>(New);
2487 }
2488
2489 FunctionDecl *Cursor = NewFD;
2490 while (true) {
2491 Cursor = Cursor->getPreviousDeclaration();
2492
2493 // If we got to the end without finding OldFD, OldFD is the newer
2494 // declaration; leave things as they are.
2495 if (!Cursor) return;
2496
2497 // If we do find OldFD, then NewFD is newer.
2498 if (Cursor == OldFD) break;
2499
2500 // Otherwise, keep looking.
2501 }
2502
2503 Old = New;
2504}
2505
Sebastian Redlc057f422009-10-23 19:23:15 +00002506void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002507 Expr **Args, unsigned NumArgs,
Richard Smith02e85f32011-04-14 22:09:26 +00002508 ADLResult &Result,
2509 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002510 // Find all of the associated namespaces and classes based on the
2511 // arguments we have.
2512 AssociatedNamespaceSet AssociatedNamespaces;
2513 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002514 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002515 AssociatedNamespaces,
2516 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002517 if (StdNamespaceIsAssociated && StdNamespace)
2518 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002519
Sebastian Redlc057f422009-10-23 19:23:15 +00002520 QualType T1, T2;
2521 if (Operator) {
2522 T1 = Args[0]->getType();
2523 if (NumArgs >= 2)
2524 T2 = Args[1]->getType();
2525 }
2526
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002527 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002528 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2529 // and let Y be the lookup set produced by argument dependent
2530 // lookup (defined as follows). If X contains [...] then Y is
2531 // empty. Otherwise Y is the set of declarations found in the
2532 // namespaces associated with the argument types as described
2533 // below. The set of declarations found by the lookup of the name
2534 // is the union of X and Y.
2535 //
2536 // Here, we compute Y and add its members to the overloaded
2537 // candidate set.
2538 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002539 NSEnd = AssociatedNamespaces.end();
2540 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002541 // When considering an associated namespace, the lookup is the
2542 // same as the lookup performed when the associated namespace is
2543 // used as a qualifier (3.4.3.2) except that:
2544 //
2545 // -- Any using-directives in the associated namespace are
2546 // ignored.
2547 //
John McCallc7e8e792009-08-07 22:18:02 +00002548 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002549 // associated classes are visible within their respective
2550 // namespaces even if they are not visible during an ordinary
2551 // lookup (11.4).
2552 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002553 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002554 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002555 // If the only declaration here is an ordinary friend, consider
2556 // it only if it was declared in an associated classes.
2557 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002558 DeclContext *LexDC = D->getLexicalDeclContext();
2559 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2560 continue;
2561 }
Mike Stump11289f42009-09-09 15:08:12 +00002562
John McCall91f61fc2010-01-26 06:04:06 +00002563 if (isa<UsingShadowDecl>(D))
2564 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002565
John McCall91f61fc2010-01-26 06:04:06 +00002566 if (isa<FunctionDecl>(D)) {
2567 if (Operator &&
2568 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2569 T1, T2, Context))
2570 continue;
John McCall8fe68082010-01-26 07:16:45 +00002571 } else if (!isa<FunctionTemplateDecl>(D))
2572 continue;
2573
2574 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002575 }
2576 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002577}
Douglas Gregor2d435302009-12-30 17:04:44 +00002578
2579//----------------------------------------------------------------------------
2580// Search for all visible declarations.
2581//----------------------------------------------------------------------------
2582VisibleDeclConsumer::~VisibleDeclConsumer() { }
2583
2584namespace {
2585
2586class ShadowContextRAII;
2587
2588class VisibleDeclsRecord {
2589public:
2590 /// \brief An entry in the shadow map, which is optimized to store a
2591 /// single declaration (the common case) but can also store a list
2592 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002593 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002594
2595private:
2596 /// \brief A mapping from declaration names to the declarations that have
2597 /// this name within a particular scope.
2598 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2599
2600 /// \brief A list of shadow maps, which is used to model name hiding.
2601 std::list<ShadowMap> ShadowMaps;
2602
2603 /// \brief The declaration contexts we have already visited.
2604 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2605
2606 friend class ShadowContextRAII;
2607
2608public:
2609 /// \brief Determine whether we have already visited this context
2610 /// (and, if not, note that we are going to visit that context now).
2611 bool visitedContext(DeclContext *Ctx) {
2612 return !VisitedContexts.insert(Ctx);
2613 }
2614
Douglas Gregor39982192010-08-15 06:18:01 +00002615 bool alreadyVisitedContext(DeclContext *Ctx) {
2616 return VisitedContexts.count(Ctx);
2617 }
2618
Douglas Gregor2d435302009-12-30 17:04:44 +00002619 /// \brief Determine whether the given declaration is hidden in the
2620 /// current scope.
2621 ///
2622 /// \returns the declaration that hides the given declaration, or
2623 /// NULL if no such declaration exists.
2624 NamedDecl *checkHidden(NamedDecl *ND);
2625
2626 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002627 void add(NamedDecl *ND) {
2628 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2629 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002630};
2631
2632/// \brief RAII object that records when we've entered a shadow context.
2633class ShadowContextRAII {
2634 VisibleDeclsRecord &Visible;
2635
2636 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2637
2638public:
2639 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2640 Visible.ShadowMaps.push_back(ShadowMap());
2641 }
2642
2643 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002644 Visible.ShadowMaps.pop_back();
2645 }
2646};
2647
2648} // end anonymous namespace
2649
Douglas Gregor2d435302009-12-30 17:04:44 +00002650NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002651 // Look through using declarations.
2652 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002653
Douglas Gregor2d435302009-12-30 17:04:44 +00002654 unsigned IDNS = ND->getIdentifierNamespace();
2655 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2656 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2657 SM != SMEnd; ++SM) {
2658 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2659 if (Pos == SM->end())
2660 continue;
2661
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002662 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002663 IEnd = Pos->second.end();
2664 I != IEnd; ++I) {
2665 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002666 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002667 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002668 Decl::IDNS_ObjCProtocol)))
2669 continue;
2670
2671 // Protocols are in distinct namespaces from everything else.
2672 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2673 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2674 (*I)->getIdentifierNamespace() != IDNS)
2675 continue;
2676
Douglas Gregor09bbc652010-01-14 15:47:35 +00002677 // Functions and function templates in the same scope overload
2678 // rather than hide. FIXME: Look for hiding based on function
2679 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002680 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002681 ND->isFunctionOrFunctionTemplate() &&
2682 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002683 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002684
Douglas Gregor2d435302009-12-30 17:04:44 +00002685 // We've found a declaration that hides this one.
2686 return *I;
2687 }
2688 }
2689
2690 return 0;
2691}
2692
2693static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2694 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002695 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002696 VisibleDeclConsumer &Consumer,
2697 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002698 if (!Ctx)
2699 return;
2700
Douglas Gregor2d435302009-12-30 17:04:44 +00002701 // Make sure we don't visit the same context twice.
2702 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2703 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002704
Douglas Gregor7454c562010-07-02 20:37:36 +00002705 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2706 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2707
Douglas Gregor2d435302009-12-30 17:04:44 +00002708 // Enumerate all of the results in this context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002709 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor2d435302009-12-30 17:04:44 +00002710 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002711 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002712 DEnd = CurCtx->decls_end();
2713 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002714 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002715 if (Result.isAcceptableDecl(ND)) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002716 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002717 Visited.add(ND);
2718 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002719 } else if (ObjCForwardProtocolDecl *ForwardProto
2720 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2721 for (ObjCForwardProtocolDecl::protocol_iterator
2722 P = ForwardProto->protocol_begin(),
2723 PEnd = ForwardProto->protocol_end();
2724 P != PEnd;
2725 ++P) {
2726 if (Result.isAcceptableDecl(*P)) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002727 Consumer.FoundDecl(*P, Visited.checkHidden(*P), Ctx, InBaseClass);
Douglas Gregora3b23b02010-12-09 21:44:02 +00002728 Visited.add(*P);
2729 }
2730 }
Douglas Gregor04246572011-02-16 01:39:26 +00002731 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002732 ObjCInterfaceDecl *IFace = Class->getForwardInterfaceDecl();
Douglas Gregor04246572011-02-16 01:39:26 +00002733 if (Result.isAcceptableDecl(IFace)) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002734 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), Ctx,
2735 InBaseClass);
Douglas Gregor04246572011-02-16 01:39:26 +00002736 Visited.add(IFace);
2737 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002738 }
Douglas Gregor04246572011-02-16 01:39:26 +00002739
Sebastian Redlbd595762010-08-31 20:53:31 +00002740 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002741 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002742 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002743 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002744 Consumer, Visited);
2745 }
2746 }
2747 }
2748
2749 // Traverse using directives for qualified name lookup.
2750 if (QualifiedNameLookup) {
2751 ShadowContextRAII Shadow(Visited);
2752 DeclContext::udir_iterator I, E;
2753 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002754 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002755 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002756 }
2757 }
2758
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002759 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002760 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002761 if (!Record->hasDefinition())
2762 return;
2763
Douglas Gregor2d435302009-12-30 17:04:44 +00002764 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2765 BEnd = Record->bases_end();
2766 B != BEnd; ++B) {
2767 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002768
Douglas Gregor2d435302009-12-30 17:04:44 +00002769 // Don't look into dependent bases, because name lookup can't look
2770 // there anyway.
2771 if (BaseType->isDependentType())
2772 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002773
Douglas Gregor2d435302009-12-30 17:04:44 +00002774 const RecordType *Record = BaseType->getAs<RecordType>();
2775 if (!Record)
2776 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002777
Douglas Gregor2d435302009-12-30 17:04:44 +00002778 // FIXME: It would be nice to be able to determine whether referencing
2779 // a particular member would be ambiguous. For example, given
2780 //
2781 // struct A { int member; };
2782 // struct B { int member; };
2783 // struct C : A, B { };
2784 //
2785 // void f(C *c) { c->### }
2786 //
2787 // accessing 'member' would result in an ambiguity. However, we
2788 // could be smart enough to qualify the member with the base
2789 // class, e.g.,
2790 //
2791 // c->B::member
2792 //
2793 // or
2794 //
2795 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002796
Douglas Gregor2d435302009-12-30 17:04:44 +00002797 // Find results in this base class (and its bases).
2798 ShadowContextRAII Shadow(Visited);
2799 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002800 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002801 }
2802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002804 // Traverse the contexts of Objective-C classes.
2805 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2806 // Traverse categories.
2807 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2808 Category; Category = Category->getNextClassCategory()) {
2809 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002810 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002811 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002812 }
2813
2814 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002815 for (ObjCInterfaceDecl::all_protocol_iterator
2816 I = IFace->all_referenced_protocol_begin(),
2817 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002818 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002819 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002820 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002821 }
2822
2823 // Traverse the superclass.
2824 if (IFace->getSuperClass()) {
2825 ShadowContextRAII Shadow(Visited);
2826 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002827 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002828 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829
Douglas Gregor0b59e802010-04-19 18:02:19 +00002830 // If there is an implementation, traverse it. We do this to find
2831 // synthesized ivars.
2832 if (IFace->getImplementation()) {
2833 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002834 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002835 QualifiedNameLookup, true, Consumer, Visited);
2836 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002837 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2838 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2839 E = Protocol->protocol_end(); I != E; ++I) {
2840 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002842 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002843 }
2844 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2845 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2846 E = Category->protocol_end(); I != E; ++I) {
2847 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002849 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002851
Douglas Gregor0b59e802010-04-19 18:02:19 +00002852 // If there is an implementation, traverse it.
2853 if (Category->getImplementation()) {
2854 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002856 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002858 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002859}
2860
2861static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2862 UnqualUsingDirectiveSet &UDirs,
2863 VisibleDeclConsumer &Consumer,
2864 VisibleDeclsRecord &Visited) {
2865 if (!S)
2866 return;
2867
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002868 if (!S->getEntity() ||
2869 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00002870 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002871 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2872 // Walk through the declarations in this Scope.
2873 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2874 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002875 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002876 if (Result.isAcceptableDecl(ND)) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002877 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002878 Visited.add(ND);
2879 }
2880 }
2881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002882
Douglas Gregor66230062010-03-15 14:33:29 +00002883 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002884 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002885 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002886 // Look into this scope's declaration context, along with any of its
2887 // parent lookup contexts (e.g., enclosing classes), up to the point
2888 // where we hit the context stored in the next outer scope.
2889 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002890 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002891
Douglas Gregorea166062010-03-15 15:26:48 +00002892 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002893 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002894 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2895 if (Method->isInstanceMethod()) {
2896 // For instance methods, look for ivars in the method's interface.
2897 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2898 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002899 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian97d744b2011-08-31 22:24:06 +00002901 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002902 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002903 }
2904
2905 // We've already performed all of the name lookup that we need
2906 // to for Objective-C methods; the next context will be the
2907 // outer scope.
2908 break;
2909 }
2910
Douglas Gregor2d435302009-12-30 17:04:44 +00002911 if (Ctx->isFunctionOrMethod())
2912 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913
2914 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002915 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002916 }
2917 } else if (!S->getParent()) {
2918 // Look into the translation unit scope. We walk through the translation
2919 // unit's declaration context, because the Scope itself won't have all of
2920 // the declarations if we loaded a precompiled header.
2921 // FIXME: We would like the translation unit's Scope object to point to the
2922 // translation unit, so we don't need this special "if" branch. However,
2923 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002924 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00002925 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002926 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002927 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002928 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002929 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930 }
2931
Douglas Gregor2d435302009-12-30 17:04:44 +00002932 if (Entity) {
2933 // Lookup visible declarations in any namespaces found by using
2934 // directives.
2935 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2936 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2937 for (; UI != UEnd; ++UI)
2938 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002939 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002940 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002941 }
2942
2943 // Lookup names in the parent scope.
2944 ShadowContextRAII Shadow(Visited);
2945 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2946}
2947
2948void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002949 VisibleDeclConsumer &Consumer,
2950 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002951 // Determine the set of using directives available during
2952 // unqualified name lookup.
2953 Scope *Initial = S;
2954 UnqualUsingDirectiveSet UDirs;
2955 if (getLangOptions().CPlusPlus) {
2956 // Find the first namespace or translation-unit scope.
2957 while (S && !isNamespaceOrTranslationUnitScope(S))
2958 S = S->getParent();
2959
2960 UDirs.visitScopeChain(Initial, S);
2961 }
2962 UDirs.done();
2963
2964 // Look for visible declarations.
2965 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2966 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002967 if (!IncludeGlobalScope)
2968 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002969 ShadowContextRAII Shadow(Visited);
2970 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2971}
2972
2973void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002974 VisibleDeclConsumer &Consumer,
2975 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002976 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2977 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002978 if (!IncludeGlobalScope)
2979 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002980 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002981 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002982 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002983}
2984
Chris Lattner43e7f312011-02-18 02:08:43 +00002985/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002986/// If GnuLabelLoc is a valid source location, then this is a definition
2987/// of an __label__ label name, otherwise it is a normal label definition
2988/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00002989LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002990 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002991 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00002992 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002993
2994 if (GnuLabelLoc.isValid()) {
2995 // Local label definitions always shadow existing labels.
2996 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
2997 Scope *S = CurScope;
2998 PushOnScopeChains(Res, S, true);
2999 return cast<LabelDecl>(Res);
3000 }
3001
3002 // Not a GNU local label.
3003 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3004 // If we found a label, check to see if it is in the same context as us.
3005 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003006 if (Res && Res->getDeclContext() != CurContext)
3007 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003008 if (Res == 0) {
3009 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003010 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3011 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003012 assert(S && "Not in a function?");
3013 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003014 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003015 return cast<LabelDecl>(Res);
3016}
3017
3018//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003019// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003020//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003021
3022namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003023
3024typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003025typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003026
3027static const unsigned MaxTypoDistanceResultSets = 5;
3028
Douglas Gregor2d435302009-12-30 17:04:44 +00003029class TypoCorrectionConsumer : public VisibleDeclConsumer {
3030 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003031 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003032
3033 /// \brief The results found that have the smallest edit distance
3034 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003035 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003036 /// The pointer value being set to the current DeclContext indicates
3037 /// whether there is a keyword with this name.
3038 TypoEditDistanceMap BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003039
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003040 /// \brief The worst of the best N edit distances found so far.
3041 unsigned MaxEditDistance;
3042
3043 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044
Douglas Gregor2d435302009-12-30 17:04:44 +00003045public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003046 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003047 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003048 MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3049 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003050
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003051 ~TypoCorrectionConsumer() {
3052 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3053 IEnd = BestResults.end();
3054 I != IEnd;
3055 ++I)
3056 delete I->second;
3057 }
3058
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003059 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3060 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003061 void FoundName(StringRef Name);
3062 void addKeywordResult(StringRef Keyword);
3063 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003064 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003065 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003066
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003067 typedef TypoResultsMap::iterator result_iterator;
3068 typedef TypoEditDistanceMap::iterator distance_iterator;
3069 distance_iterator begin() { return BestResults.begin(); }
3070 distance_iterator end() { return BestResults.end(); }
3071 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003072 unsigned size() const { return BestResults.size(); }
3073 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003074
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003075 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003076 return (*BestResults.begin()->second)[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003077 }
3078
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003079 unsigned getMaxEditDistance() const {
3080 return MaxEditDistance;
3081 }
3082
3083 unsigned getBestEditDistance() {
3084 return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3085 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003086};
3087
3088}
3089
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003090void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003091 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003092 // Don't consider hidden names for typo correction.
3093 if (Hiding)
3094 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095
Douglas Gregor2d435302009-12-30 17:04:44 +00003096 // Only consider entities with identifiers for names, ignoring
3097 // special names (constructors, overloaded operators, selectors,
3098 // etc.).
3099 IdentifierInfo *Name = ND->getIdentifier();
3100 if (!Name)
3101 return;
3102
Douglas Gregor57756ea2010-10-14 22:11:03 +00003103 FoundName(Name->getName());
3104}
3105
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003106void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003107 // Use a simple length-based heuristic to determine the minimum possible
3108 // edit distance. If the minimum isn't good enough, bail out early.
3109 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003110 if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
Douglas Gregor93910a52010-10-19 19:39:10 +00003111 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003113 // Compute an upper bound on the allowable edit distance, so that the
3114 // edit-distance algorithm can short-circuit.
Jay Foad72e705e2011-04-23 09:06:00 +00003115 unsigned UpperBound =
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003116 std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003117
Douglas Gregor2d435302009-12-30 17:04:44 +00003118 // Compute the edit distance between the typo and the name of this
3119 // entity. If this edit distance is not worse than the best edit
3120 // distance we've seen so far, add it to the list of results.
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003121 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003123 if (ED > MaxEditDistance) {
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003124 // This result is worse than the best results we've seen so far;
3125 // ignore it.
3126 return;
3127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003128
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003129 addName(Name, NULL, ED);
Douglas Gregor2d435302009-12-30 17:04:44 +00003130}
3131
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003132void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003133 // Compute the edit distance between the typo and this keyword.
3134 // If this edit distance is not worse than the best edit
3135 // distance we've seen so far, add it to the list of results.
3136 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003137 if (ED > MaxEditDistance) {
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003138 // This result is worse than the best results we've seen so far;
3139 // ignore it.
3140 return;
3141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003142
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003143 addName(Keyword, NULL, ED, NULL, true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003144}
3145
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003146void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003147 NamedDecl *ND,
3148 unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003149 NestedNameSpecifier *NNS,
3150 bool isKeyword) {
3151 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3152 if (isKeyword) TC.makeKeyword();
3153 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003154}
3155
3156void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003157 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003158 TypoResultsMap *& Map = BestResults[Correction.getEditDistance()];
3159 if (!Map)
3160 Map = new TypoResultsMap;
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003161
3162 TypoCorrection &CurrentCorrection = (*Map)[Name];
3163 if (!CurrentCorrection ||
3164 // FIXME: The following should be rolled up into an operator< on
3165 // TypoCorrection with a more principled definition.
3166 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3167 Correction.getAsString(SemaRef.getLangOptions()) <
3168 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3169 CurrentCorrection = Correction;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003170
3171 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003172 TypoEditDistanceMap::iterator Last = BestResults.end();
3173 --Last;
3174 delete Last->second;
3175 BestResults.erase(Last);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003176 }
3177}
3178
3179namespace {
3180
3181class SpecifierInfo {
3182 public:
3183 DeclContext* DeclCtx;
3184 NestedNameSpecifier* NameSpecifier;
3185 unsigned EditDistance;
3186
3187 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3188 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3189};
3190
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003191typedef SmallVector<DeclContext*, 4> DeclContextList;
3192typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003193
3194class NamespaceSpecifierSet {
3195 ASTContext &Context;
3196 DeclContextList CurContextChain;
3197 bool isSorted;
3198
3199 SpecifierInfoList Specifiers;
3200 llvm::SmallSetVector<unsigned, 4> Distances;
3201 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3202
3203 /// \brief Helper for building the list of DeclContexts between the current
3204 /// context and the top of the translation unit
3205 static DeclContextList BuildContextChain(DeclContext *Start);
3206
3207 void SortNamespaces();
3208
3209 public:
3210 explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003211 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3212 isSorted(true) {}
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003213
3214 /// \brief Add the namespace to the set, computing the corresponding
3215 /// NestedNameSpecifier and its distance in the process.
3216 void AddNamespace(NamespaceDecl *ND);
3217
3218 typedef SpecifierInfoList::iterator iterator;
3219 iterator begin() {
3220 if (!isSorted) SortNamespaces();
3221 return Specifiers.begin();
3222 }
3223 iterator end() { return Specifiers.end(); }
3224};
3225
3226}
3227
3228DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003229 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003230 DeclContextList Chain;
3231 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3232 DC = DC->getLookupParent()) {
3233 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3234 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3235 !(ND && ND->isAnonymousNamespace()))
3236 Chain.push_back(DC->getPrimaryContext());
3237 }
3238 return Chain;
3239}
3240
3241void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003242 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003243 sortedDistances.append(Distances.begin(), Distances.end());
3244
3245 if (sortedDistances.size() > 1)
3246 std::sort(sortedDistances.begin(), sortedDistances.end());
3247
3248 Specifiers.clear();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003249 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003250 DIEnd = sortedDistances.end();
3251 DI != DIEnd; ++DI) {
3252 SpecifierInfoList &SpecList = DistanceMap[*DI];
3253 Specifiers.append(SpecList.begin(), SpecList.end());
3254 }
3255
3256 isSorted = true;
3257}
3258
3259void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003260 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003261 NestedNameSpecifier *NNS = NULL;
3262 unsigned NumSpecifiers = 0;
3263 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3264
3265 // Eliminate common elements from the two DeclContext chains
3266 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3267 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003268 C != CEnd && !NamespaceDeclChain.empty() &&
3269 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003270 NamespaceDeclChain.pop_back();
3271 }
3272
3273 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3274 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3275 CEnd = NamespaceDeclChain.rend();
3276 C != CEnd; ++C) {
3277 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3278 if (ND) {
3279 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3280 ++NumSpecifiers;
3281 }
3282 }
3283
3284 isSorted = false;
3285 Distances.insert(NumSpecifiers);
3286 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003287}
3288
Douglas Gregord507d772010-10-20 03:06:34 +00003289/// \brief Perform name lookup for a possible result for typo correction.
3290static void LookupPotentialTypoResult(Sema &SemaRef,
3291 LookupResult &Res,
3292 IdentifierInfo *Name,
3293 Scope *S, CXXScopeSpec *SS,
3294 DeclContext *MemberContext,
3295 bool EnteringContext,
3296 Sema::CorrectTypoContext CTC) {
3297 Res.suppressDiagnostics();
3298 Res.clear();
3299 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003301 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3302 if (CTC == Sema::CTC_ObjCIvarLookup) {
3303 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3304 Res.addDecl(Ivar);
3305 Res.resolveKind();
3306 return;
3307 }
3308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003309
Douglas Gregord507d772010-10-20 03:06:34 +00003310 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3311 Res.addDecl(Prop);
3312 Res.resolveKind();
3313 return;
3314 }
3315 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003316
Douglas Gregord507d772010-10-20 03:06:34 +00003317 SemaRef.LookupQualifiedName(Res, MemberContext);
3318 return;
3319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003320
3321 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003322 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323
Douglas Gregord507d772010-10-20 03:06:34 +00003324 // Fake ivar lookup; this should really be part of
3325 // LookupParsedName.
3326 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3327 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003329 (Res.isSingleResult() &&
3330 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003332 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3333 Res.addDecl(IV);
3334 Res.resolveKind();
3335 }
3336 }
3337 }
3338}
3339
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003340/// \brief Add keywords to the consumer as possible typo corrections.
3341static void AddKeywordsToConsumer(Sema &SemaRef,
3342 TypoCorrectionConsumer &Consumer,
3343 Scope *S, Sema::CorrectTypoContext CTC) {
3344 // Add context-dependent keywords.
3345 bool WantTypeSpecifiers = false;
3346 bool WantExpressionKeywords = false;
3347 bool WantCXXNamedCasts = false;
3348 bool WantRemainingKeywords = false;
3349 switch (CTC) {
3350 case Sema::CTC_Unknown:
3351 WantTypeSpecifiers = true;
3352 WantExpressionKeywords = true;
3353 WantCXXNamedCasts = true;
3354 WantRemainingKeywords = true;
3355
3356 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3357 if (Method->getClassInterface() &&
3358 Method->getClassInterface()->getSuperClass())
3359 Consumer.addKeywordResult("super");
3360
3361 break;
3362
3363 case Sema::CTC_NoKeywords:
3364 break;
3365
3366 case Sema::CTC_Type:
3367 WantTypeSpecifiers = true;
3368 break;
3369
3370 case Sema::CTC_ObjCMessageReceiver:
3371 Consumer.addKeywordResult("super");
3372 // Fall through to handle message receivers like expressions.
3373
3374 case Sema::CTC_Expression:
3375 if (SemaRef.getLangOptions().CPlusPlus)
3376 WantTypeSpecifiers = true;
3377 WantExpressionKeywords = true;
3378 // Fall through to get C++ named casts.
3379
3380 case Sema::CTC_CXXCasts:
3381 WantCXXNamedCasts = true;
3382 break;
3383
3384 case Sema::CTC_ObjCPropertyLookup:
3385 // FIXME: Add "isa"?
3386 break;
3387
3388 case Sema::CTC_MemberLookup:
3389 if (SemaRef.getLangOptions().CPlusPlus)
3390 Consumer.addKeywordResult("template");
3391 break;
3392
3393 case Sema::CTC_ObjCIvarLookup:
3394 break;
3395 }
3396
3397 if (WantTypeSpecifiers) {
3398 // Add type-specifier keywords to the set of results.
3399 const char *CTypeSpecs[] = {
3400 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003401 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003402 "_Complex", "_Imaginary",
3403 // storage-specifiers as well
3404 "extern", "inline", "static", "typedef"
3405 };
3406
3407 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3408 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3409 Consumer.addKeywordResult(CTypeSpecs[I]);
3410
3411 if (SemaRef.getLangOptions().C99)
3412 Consumer.addKeywordResult("restrict");
3413 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3414 Consumer.addKeywordResult("bool");
Douglas Gregor3b22a882011-07-01 21:27:45 +00003415 else if (SemaRef.getLangOptions().C99)
3416 Consumer.addKeywordResult("_Bool");
3417
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003418 if (SemaRef.getLangOptions().CPlusPlus) {
3419 Consumer.addKeywordResult("class");
3420 Consumer.addKeywordResult("typename");
3421 Consumer.addKeywordResult("wchar_t");
3422
3423 if (SemaRef.getLangOptions().CPlusPlus0x) {
3424 Consumer.addKeywordResult("char16_t");
3425 Consumer.addKeywordResult("char32_t");
3426 Consumer.addKeywordResult("constexpr");
3427 Consumer.addKeywordResult("decltype");
3428 Consumer.addKeywordResult("thread_local");
3429 }
3430 }
3431
3432 if (SemaRef.getLangOptions().GNUMode)
3433 Consumer.addKeywordResult("typeof");
3434 }
3435
3436 if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3437 Consumer.addKeywordResult("const_cast");
3438 Consumer.addKeywordResult("dynamic_cast");
3439 Consumer.addKeywordResult("reinterpret_cast");
3440 Consumer.addKeywordResult("static_cast");
3441 }
3442
3443 if (WantExpressionKeywords) {
3444 Consumer.addKeywordResult("sizeof");
3445 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3446 Consumer.addKeywordResult("false");
3447 Consumer.addKeywordResult("true");
3448 }
3449
3450 if (SemaRef.getLangOptions().CPlusPlus) {
3451 const char *CXXExprs[] = {
3452 "delete", "new", "operator", "throw", "typeid"
3453 };
3454 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3455 for (unsigned I = 0; I != NumCXXExprs; ++I)
3456 Consumer.addKeywordResult(CXXExprs[I]);
3457
3458 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3459 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3460 Consumer.addKeywordResult("this");
3461
3462 if (SemaRef.getLangOptions().CPlusPlus0x) {
3463 Consumer.addKeywordResult("alignof");
3464 Consumer.addKeywordResult("nullptr");
3465 }
3466 }
3467 }
3468
3469 if (WantRemainingKeywords) {
3470 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3471 // Statements.
3472 const char *CStmts[] = {
3473 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3474 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3475 for (unsigned I = 0; I != NumCStmts; ++I)
3476 Consumer.addKeywordResult(CStmts[I]);
3477
3478 if (SemaRef.getLangOptions().CPlusPlus) {
3479 Consumer.addKeywordResult("catch");
3480 Consumer.addKeywordResult("try");
3481 }
3482
3483 if (S && S->getBreakParent())
3484 Consumer.addKeywordResult("break");
3485
3486 if (S && S->getContinueParent())
3487 Consumer.addKeywordResult("continue");
3488
3489 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3490 Consumer.addKeywordResult("case");
3491 Consumer.addKeywordResult("default");
3492 }
3493 } else {
3494 if (SemaRef.getLangOptions().CPlusPlus) {
3495 Consumer.addKeywordResult("namespace");
3496 Consumer.addKeywordResult("template");
3497 }
3498
3499 if (S && S->isClassScope()) {
3500 Consumer.addKeywordResult("explicit");
3501 Consumer.addKeywordResult("friend");
3502 Consumer.addKeywordResult("mutable");
3503 Consumer.addKeywordResult("private");
3504 Consumer.addKeywordResult("protected");
3505 Consumer.addKeywordResult("public");
3506 Consumer.addKeywordResult("virtual");
3507 }
3508 }
3509
3510 if (SemaRef.getLangOptions().CPlusPlus) {
3511 Consumer.addKeywordResult("using");
3512
3513 if (SemaRef.getLangOptions().CPlusPlus0x)
3514 Consumer.addKeywordResult("static_assert");
3515 }
3516 }
3517}
3518
Douglas Gregor2d435302009-12-30 17:04:44 +00003519/// \brief Try to "correct" a typo in the source code by finding
3520/// visible declarations whose names are similar to the name that was
3521/// present in the source code.
3522///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003523/// \param TypoName the \c DeclarationNameInfo structure that contains
3524/// the name that was present in the source code along with its location.
3525///
3526/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003527///
3528/// \param S the scope in which name lookup occurs.
3529///
3530/// \param SS the nested-name-specifier that precedes the name we're
3531/// looking for, if present.
3532///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003533/// \param MemberContext if non-NULL, the context in which to look for
3534/// a member access expression.
3535///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003537/// the nested-name-specifier SS.
3538///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003539/// \param CTC The context in which typo correction occurs, which impacts the
3540/// set of keywords permitted.
3541///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003542/// \param OPT when non-NULL, the search for visible declarations will
3543/// also walk the protocols in the qualified interfaces of \p OPT.
3544///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003545/// \returns a \c TypoCorrection containing the corrected name if the typo
3546/// along with information such as the \c NamedDecl where the corrected name
3547/// was declared, and any additional \c NestedNameSpecifier needed to access
3548/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3549TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3550 Sema::LookupNameKind LookupKind,
3551 Scope *S, CXXScopeSpec *SS,
3552 DeclContext *MemberContext,
3553 bool EnteringContext,
3554 CorrectTypoContext CTC,
3555 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00003556 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003557 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558
Douglas Gregor2d435302009-12-30 17:04:44 +00003559 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003560 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003561 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003562 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003563
3564 // If the scope specifier itself was invalid, don't try to correct
3565 // typos.
3566 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003567 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003568
3569 // Never try to correct typos during template deduction or
3570 // instantiation.
3571 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003572 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003574 NamespaceSpecifierSet Namespaces(Context, CurContext);
3575
3576 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003578 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003579 bool IsUnqualifiedLookup = false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003580 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003581 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003582
3583 // Look in qualified interfaces.
3584 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585 for (ObjCObjectPointerType::qual_iterator
3586 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003587 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003588 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003589 }
3590 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003591 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3592 if (!DC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003593 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003594
Douglas Gregor87074f12010-10-20 01:32:02 +00003595 // Provide a stop gap for files that are just seriously broken. Trying
3596 // to correct all typos can turn into a HUGE performance penalty, causing
3597 // some files to take minutes to get rejected by the parser.
3598 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003599 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003600 ++TyposCorrected;
3601
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003602 LookupVisibleDecls(DC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003603 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003604 IsUnqualifiedLookup = true;
3605 UnqualifiedTyposCorrectedMap::iterator Cached
3606 = UnqualifiedTyposCorrected.find(Typo);
3607 if (Cached == UnqualifiedTyposCorrected.end()) {
3608 // Provide a stop gap for files that are just seriously broken. Trying
3609 // to correct all typos can turn into a HUGE performance penalty, causing
3610 // some files to take minutes to get rejected by the parser.
3611 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003612 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613
Douglas Gregor87074f12010-10-20 01:32:02 +00003614 // For unqualified lookup, look through all of the names that we have
3615 // seen in this translation unit.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor87074f12010-10-20 01:32:02 +00003617 IEnd = Context.Idents.end();
3618 I != IEnd; ++I)
3619 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003620
Douglas Gregor87074f12010-10-20 01:32:02 +00003621 // Walk through identifiers in external identifier sources.
3622 if (IdentifierInfoLookup *External
Douglas Gregor57756ea2010-10-14 22:11:03 +00003623 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenekb4ea9a82010-11-07 06:11:33 +00003624 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor87074f12010-10-20 01:32:02 +00003625 do {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003626 StringRef Name = Iter->Next();
Douglas Gregor87074f12010-10-20 01:32:02 +00003627 if (Name.empty())
3628 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003629
Douglas Gregor87074f12010-10-20 01:32:02 +00003630 Consumer.FoundName(Name);
3631 } while (true);
3632 }
3633 } else {
3634 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3635 // end up adding the keyword below.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003636 if (!Cached->second)
3637 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003639 if (!Cached->second.isKeyword())
3640 Consumer.addCorrection(Cached->second);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003641 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003642 }
3643
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003644 AddKeywordsToConsumer(*this, Consumer, S, CTC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003646 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003647 if (Consumer.empty()) {
3648 // If this was an unqualified lookup, note that no correction was found.
3649 if (IsUnqualifiedLookup)
3650 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003651
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003652 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003653 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003654
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003656 // made. Otherwise, we don't even both looking at the results.
3657 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor87074f12010-10-20 01:32:02 +00003658 if (ED > 0 && Typo->getName().size() / ED < 3) {
3659 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003660 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003661 (void)UnqualifiedTyposCorrected[Typo];
3662
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003663 return TypoCorrection();
3664 }
3665
3666 // Build the NestedNameSpecifiers for the KnownNamespaces
3667 if (getLangOptions().CPlusPlus) {
3668 // Load any externally-known namespaces.
3669 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003670 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003671 LoadedExternalKnownNamespaces = true;
3672 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3673 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3674 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3675 }
3676
3677 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3678 KNI = KnownNamespaces.begin(),
3679 KNIEnd = KnownNamespaces.end();
3680 KNI != KNIEnd; ++KNI)
3681 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003682 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003683
3684 // Weed out any names that could not be found by name lookup.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003685 llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3686 LookupResult TmpRes(*this, TypoName, LookupKind);
3687 TmpRes.suppressDiagnostics();
3688 while (!Consumer.empty()) {
3689 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3690 unsigned ED = DI->first;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003691 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3692 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003693 I != IEnd; /* Increment in loop. */) {
3694 // If the item already has been looked up or is a keyword, keep it
3695 if (I->second.isResolved()) {
3696 ++I;
3697 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003698 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003699
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003700 // Perform name lookup on this name.
3701 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3702 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3703 EnteringContext, CTC);
3704
3705 switch (TmpRes.getResultKind()) {
3706 case LookupResult::NotFound:
3707 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003708 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003709 QualifiedResults.insert(Name);
3710 // We didn't find this name in our scope, or didn't like what we found;
3711 // ignore it.
3712 {
3713 TypoCorrectionConsumer::result_iterator Next = I;
3714 ++Next;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003715 DI->second->erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003716 I = Next;
3717 }
3718 break;
3719
3720 case LookupResult::Ambiguous:
3721 // We don't deal with ambiguities.
3722 return TypoCorrection();
3723
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003724 case LookupResult::FoundOverloaded: {
3725 // Store all of the Decls for overloaded symbols
3726 for (LookupResult::iterator TRD = TmpRes.begin(),
3727 TRDEnd = TmpRes.end();
3728 TRD != TRDEnd; ++TRD)
3729 I->second.addCorrectionDecl(*TRD);
3730 ++I;
3731 break;
3732 }
3733
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003734 case LookupResult::Found:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003735 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3736 ++I;
3737 break;
3738 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003740
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003741 if (DI->second->empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003742 Consumer.erase(DI);
3743 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3744 // If there are results in the closest possible bucket, stop
3745 break;
3746
3747 // Only perform the qualified lookups for C++
3748 if (getLangOptions().CPlusPlus) {
3749 TmpRes.suppressDiagnostics();
3750 for (llvm::SmallPtrSet<IdentifierInfo*,
3751 16>::iterator QRI = QualifiedResults.begin(),
3752 QRIEnd = QualifiedResults.end();
3753 QRI != QRIEnd; ++QRI) {
3754 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3755 NIEnd = Namespaces.end();
3756 NI != NIEnd; ++NI) {
3757 DeclContext *Ctx = NI->DeclCtx;
3758 unsigned QualifiedED = ED + NI->EditDistance;
3759
3760 // Stop searching once the namespaces are too far away to create
3761 // acceptable corrections for this identifier (since the namespaces
3762 // are sorted in ascending order by edit distance)
3763 if (QualifiedED > Consumer.getMaxEditDistance()) break;
3764
3765 TmpRes.clear();
3766 TmpRes.setLookupName(*QRI);
3767 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3768
3769 switch (TmpRes.getResultKind()) {
3770 case LookupResult::Found:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003771 Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3772 QualifiedED, NI->NameSpecifier);
3773 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003774 case LookupResult::FoundOverloaded: {
3775 TypoCorrection corr(&Context.Idents.get((*QRI)->getName()), NULL,
3776 NI->NameSpecifier, QualifiedED);
3777 for (LookupResult::iterator TRD = TmpRes.begin(),
3778 TRDEnd = TmpRes.end();
3779 TRD != TRDEnd; ++TRD)
3780 corr.addCorrectionDecl(*TRD);
3781 Consumer.addCorrection(corr);
3782 break;
3783 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003784 case LookupResult::NotFound:
3785 case LookupResult::NotFoundInCurrentInstantiation:
3786 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003787 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003788 break;
3789 }
3790 }
3791 }
3792 }
3793
3794 QualifiedResults.clear();
3795 }
3796
3797 // No corrections remain...
3798 if (Consumer.empty()) return TypoCorrection();
3799
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003800 TypoResultsMap &BestResults = *Consumer.begin()->second;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003801 ED = Consumer.begin()->first;
3802
3803 if (ED > 0 && Typo->getName().size() / ED < 3) {
3804 // If this was an unqualified lookup, note that no correction was found.
3805 if (IsUnqualifiedLookup)
3806 (void)UnqualifiedTyposCorrected[Typo];
3807
3808 return TypoCorrection();
3809 }
3810
3811 // If we have multiple possible corrections, eliminate the ones where we
3812 // added namespace qualifiers to try to resolve the ambiguity (and to favor
3813 // corrections without additional namespace qualifiers)
3814 if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3815 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003816 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3817 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003818 I != IEnd; /* Increment in loop. */) {
3819 if (I->second.getCorrectionSpecifier() != NULL) {
3820 TypoCorrectionConsumer::result_iterator Cur = I;
3821 ++I;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003822 DI->second->erase(Cur);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003823 } else ++I;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003825 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003826
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003827 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003828 if (BestResults.size() == 1) {
3829 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3830 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003831
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003832 // Don't correct to a keyword that's the same as the typo; the keyword
3833 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003834 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3835
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003836 // Record the correction for unqualified lookup.
3837 if (IsUnqualifiedLookup)
3838 UnqualifiedTyposCorrected[Typo] = Result;
3839
3840 return Result;
3841 }
3842 else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3843 && BestResults["super"].isKeyword()) {
3844 // Prefer 'super' when we're completing in a message-receiver
3845 // context.
3846
3847 // Don't correct to a keyword that's the same as the typo; the keyword
3848 // wasn't actually in scope.
3849 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850
Douglas Gregor87074f12010-10-20 01:32:02 +00003851 // Record the correction for unqualified lookup.
3852 if (IsUnqualifiedLookup)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003853 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003855 return BestResults["super"];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003856 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003857
Douglas Gregor87074f12010-10-20 01:32:02 +00003858 if (IsUnqualifiedLookup)
3859 (void)UnqualifiedTyposCorrected[Typo];
3860
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003861 return TypoCorrection();
3862}
3863
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003864void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
3865 if (!CDecl) return;
3866
3867 if (isKeyword())
3868 CorrectionDecls.clear();
3869
3870 CorrectionDecls.push_back(CDecl);
3871
3872 if (!CorrectionName)
3873 CorrectionName = CDecl->getDeclName();
3874}
3875
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003876std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3877 if (CorrectionNameSpec) {
3878 std::string tmpBuffer;
3879 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3880 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3881 return PrefixOStream.str() + CorrectionName.getAsString();
3882 }
3883
3884 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00003885}