blob: 5964d7232a85bde74088422de43621d06d16b588 [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
Sean Hunt308742c2011-06-04 04:32:43 +000017#include "clang/Sema/Overload.h"
John McCall19510852010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
John McCall5f1e0942010-08-24 08:50:51 +000019#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Axel Naumannf8291a12011-02-24 16:47:47 +000022#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregord8bba9c2011-06-28 16:20:02 +000023#include "clang/Sema/TypoCorrection.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000024#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000025#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000026#include "clang/AST/Decl.h"
27#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000029#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000030#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000031#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000033#include "clang/Basic/LangOptions.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000036#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000037#include "llvm/ADT/StringMap.h"
Chris Lattnerb5f65472011-07-18 01:54:02 +000038#include "llvm/ADT/TinyPtrVector.h"
John McCall6e247262009-10-10 05:48:19 +000039#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000040#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000041#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000042#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000043#include <vector>
44#include <iterator>
45#include <utility>
46#include <algorithm>
Douglas Gregord8bba9c2011-06-28 16:20:02 +000047#include <map>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000048
49using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000050using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000051
John McCalld7be78a2009-11-10 07:01:13 +000052namespace {
53 class UnqualUsingEntry {
54 const DeclContext *Nominated;
55 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000056
John McCalld7be78a2009-11-10 07:01:13 +000057 public:
58 UnqualUsingEntry(const DeclContext *Nominated,
59 const DeclContext *CommonAncestor)
60 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
61 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000062
John McCalld7be78a2009-11-10 07:01:13 +000063 const DeclContext *getCommonAncestor() const {
64 return CommonAncestor;
65 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000066
John McCalld7be78a2009-11-10 07:01:13 +000067 const DeclContext *getNominatedNamespace() const {
68 return Nominated;
69 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000070
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000076
John McCalld7be78a2009-11-10 07:01:13 +000077 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
78 return E.getCommonAncestor() < DC;
79 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000080
John McCalld7be78a2009-11-10 07:01:13 +000081 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
82 return DC < E.getCommonAncestor();
83 }
84 };
85 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000086
John McCalld7be78a2009-11-10 07:01:13 +000087 /// A collection of using directives, as used by C++ unqualified
88 /// lookup.
89 class UnqualUsingDirectiveSet {
Chris Lattner5f9e2722011-07-23 10:55:15 +000090 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000091
John McCalld7be78a2009-11-10 07:01:13 +000092 ListTy list;
93 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000094
John McCalld7be78a2009-11-10 07:01:13 +000095 public:
96 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000097
John McCalld7be78a2009-11-10 07:01:13 +000098 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000099 // C++ [namespace.udir]p1:
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000106
John McCalld7be78a2009-11-10 07:01:13 +0000107 for (; S; S = S->getParent()) {
John McCalld7be78a2009-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 Takumidfbb02a2011-01-27 07:10:08 +0000114
John McCalld7be78a2009-11-10 07:01:13 +0000115 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000116 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000117 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000118 }
119 }
John McCalld7be78a2009-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 Lattner5f9e2722011-07-23 10:55:15 +0000151 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000184 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000185
John McCalld7be78a2009-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 McCalld7be78a2009-11-10 07:01:13 +0000193 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000194
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000200 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000201 UnqualUsingEntry::Comparator());
202 }
203 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000204}
205
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000206// Retrieve the set of identifier namespaces that correspond to a
207// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000208static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
209 bool CPlusPlus,
210 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000211 unsigned IDNS = 0;
212 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000213 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000214 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000215 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000216 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000217 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000219 if (Redeclaration)
220 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000221 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000222 break;
223
John McCall76d32642010-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 Gregor2a3009a2009-02-03 19:21:40 +0000231 case Sema::LookupTagName:
John McCall0d6b1642010-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 Gregor2a3009a2009-02-03 19:21:40 +0000245 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000246 case Sema::LookupLabel:
247 IDNS = Decl::IDNS_Label;
248 break;
249
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 case Sema::LookupMemberName:
251 IDNS = Decl::IDNS_Member;
252 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000253 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000254 break;
255
256 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000257 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
258 break;
259
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000260 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000262 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000263
John McCall9f54ad42009-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 Gregor8fc463a2009-04-24 00:11:27 +0000269 case Sema::LookupObjCProtocolName:
270 IDNS = Decl::IDNS_ObjCProtocol;
271 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272
Douglas Gregor8071e422010-08-15 06:18:01 +0000273 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000274 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000275 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
276 | Decl::IDNS_Type;
277 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000278 }
279 return IDNS;
280}
281
John McCall1d7c5282009-12-18 10:40:03 +0000282void LookupResult::configure() {
Chris Lattner337e5502011-02-18 01:27:55 +0000283 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000284 isForRedeclaration());
Douglas Gregorb5b2ccb2010-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 Bagnara25777432010-08-11 22:01:17 +0000290 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-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 McCall1d7c5282009-12-18 10:40:03 +0000302}
303
John McCall2a7fb272010-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 Gregorf17b58c2010-10-22 22:08:47 +0000312 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
313 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000314 assert((Paths != NULL) == (ResultKind == Ambiguous &&
315 (Ambiguity == AmbiguousBaseSubobjectTypes ||
316 Ambiguity == AmbiguousBaseSubobjects)));
317}
John McCall2a7fb272010-08-25 05:32:35 +0000318
John McCallf36e02d2009-10-09 21:13:30 +0000319// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000320void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000321 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000322}
323
John McCall7453ed42009-11-22 00:44:51 +0000324/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000325void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000326 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327
John McCallf36e02d2009-10-09 21:13:30 +0000328 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000329 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000330 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000331 return;
332 }
333
John McCall7453ed42009-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 McCall7ba107a2009-11-18 02:36:19 +0000336 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000337 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
338 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000339 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000340 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000341 ResultKind = FoundUnresolvedValue;
342 return;
343 }
John McCallf36e02d2009-10-09 21:13:30 +0000344
John McCall6e247262009-10-10 05:48:19 +0000345 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000346 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000347
John McCallf36e02d2009-10-09 21:13:30 +0000348 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000349 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000350
John McCallf36e02d2009-10-09 21:13:30 +0000351 bool Ambiguous = false;
352 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000353 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000354
355 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000356
John McCallf36e02d2009-10-09 21:13:30 +0000357 unsigned I = 0;
358 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000359 NamedDecl *D = Decls[I]->getUnderlyingDecl();
360 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000361
Douglas Gregor7f1c5472010-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 Takumidfbb02a2011-01-27 07:10:08 +0000377
John McCall314be4e2009-11-17 07:50:12 +0000378 if (!Unique.insert(D)) {
John McCallf36e02d2009-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 Gregor7f1c5472010-08-11 14:45:53 +0000382 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000383 }
384
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000385 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000386
Douglas Gregor7f1c5472010-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 Gregor7176fff2009-01-15 00:26:24 +0000403 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000404 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000405 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000406
John McCallf36e02d2009-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 McCallfda8e122009-12-03 00:58:24 +0000416 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-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 Carlsson8b50d012009-06-26 03:37:05 +0000424
John McCallf36e02d2009-10-09 21:13:30 +0000425 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000426
John McCallfda8e122009-12-03 00:58:24 +0000427 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000428 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000429
John McCallf36e02d2009-10-09 21:13:30 +0000430 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000431 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000432 else if (HasUnresolved)
433 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000434 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000435 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000436 else
John McCalla24dc2e2009-11-17 02:14:36 +0000437 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000438}
439
John McCall7d384dd2009-11-18 07:57:50 +0000440void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000441 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-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 Gregor31a19b62009-04-01 21:51:26 +0000446}
447
John McCall7d384dd2009-11-18 07:57:50 +0000448void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000449 Paths = new CXXBasePaths;
450 Paths->swap(P);
451 addDeclsFromBasePaths(*Paths);
452 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000453 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000454}
455
John McCall7d384dd2009-11-18 07:57:50 +0000456void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000457 Paths = new CXXBasePaths;
458 Paths->swap(P);
459 addDeclsFromBasePaths(*Paths);
460 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000461 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000462}
463
Chris Lattner5f9e2722011-07-23 10:55:15 +0000464void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000465 Out << Decls.size() << " result(s)";
466 if (isAmbiguous()) Out << ", ambiguous";
467 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468
John McCallf36e02d2009-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 Gregor85910982010-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 Takumidfbb02a2011-01-27 07:10:08 +0000494
495 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
496 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000497 R.isForRedeclaration(),
498 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000499 R.addDecl(D);
Douglas Gregor6b9109e2011-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 Gregor85910982010-02-12 05:48:04 +0000510 }
511 }
512 }
513
514 return false;
515}
516
Douglas Gregor4923aa22010-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 McCallb3b50a82010-08-11 23:52:36 +0000521 // Don't do it if the class is invalid.
522 if (Class->isInvalidDecl())
523 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524
Douglas Gregor4923aa22010-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 Takumidfbb02a2011-01-27 07:10:08 +0000528
Douglas Gregor4923aa22010-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 Takumidfbb02a2011-01-27 07:10:08 +0000533
Douglas Gregor4923aa22010-07-02 20:37:36 +0000534 return false;
535}
536
537void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000538 if (!CanDeclareSpecialMemberFunction(Context, Class))
539 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000540
541 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000542 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000543 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
Douglas Gregor22584312010-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 Takumidfbb02a2011-01-27 07:10:08 +0000548
Douglas Gregora376d102010-07-02 21:50:04 +0000549 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000550 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000551 DeclareImplicitCopyAssignment(Class);
552
Sebastian Redl85ea7aa2011-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 Gregor4923aa22010-07-02 20:37:36 +0000563 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000564 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000565 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000566}
567
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000569/// special member function.
570static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
571 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000572 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000573 case DeclarationName::CXXDestructorName:
574 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000575
Douglas Gregora376d102010-07-02 21:50:04 +0000576 case DeclarationName::CXXOperatorName:
577 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578
Douglas Gregora376d102010-07-02 21:50:04 +0000579 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000580 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000581 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000582
Douglas Gregora376d102010-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 Takumidfbb02a2011-01-27 07:10:08 +0000588static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000589 DeclarationName Name,
590 const DeclContext *DC) {
591 if (!DC)
592 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000593
Douglas Gregora376d102010-07-02 21:50:04 +0000594 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000595 case DeclarationName::CXXConstructorName:
596 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000597 if (Record->getDefinition() &&
598 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000599 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000600 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000601 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000602 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000603 S.DeclareImplicitCopyConstructor(Class);
604 if (S.getLangOptions().CPlusPlus0x &&
605 Record->needsImplicitMoveConstructor())
606 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000607 }
Douglas Gregor22584312010-07-02 23:41:54 +0000608 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Douglas Gregora376d102010-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 Gregora376d102010-07-02 21:50:04 +0000615 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000616
Douglas Gregora376d102010-07-02 21:50:04 +0000617 case DeclarationName::CXXOperatorName:
618 if (Name.getCXXOverloadedOperator() != OO_Equal)
619 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000620
Sebastian Redl85ea7aa2011-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 Gregora376d102010-07-02 21:50:04 +0000632 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000633
Douglas Gregora376d102010-07-02 21:50:04 +0000634 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000635 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000636 }
637}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000638
John McCallf36e02d2009-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 Gregor85910982010-02-12 05:48:04 +0000641static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000642 bool Found = false;
643
Douglas Gregor4923aa22010-07-02 20:37:36 +0000644 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000645 if (S.getLangOptions().CPlusPlus)
646 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000647
Douglas Gregor4923aa22010-07-02 20:37:36 +0000648 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000649 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000650 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000651 NamedDecl *D = *I;
652 if (R.isAcceptableDecl(D)) {
653 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000654 Found = true;
655 }
656 }
John McCallf36e02d2009-10-09 21:13:30 +0000657
Douglas Gregor85910982010-02-12 05:48:04 +0000658 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
659 return true;
660
Douglas Gregor48026d22010-01-11 18:40:55 +0000661 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000668 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-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 McCall5e1cdac2011-10-07 06:10:15 +0000672 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000673 return Found;
674
675 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000676 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000681
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000682 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-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 Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000691
Douglas Gregor48026d22010-01-11 18:40:55 +0000692 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-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 Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000699 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-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 McCall2a7fb272010-08-25 05:32:35 +0000702 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000703 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000704
705 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000706 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
707 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000708
Chandler Carruthaaa1a892010-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 McCalle23cf432010-12-14 08:05:40 +0000712 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
713 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000714 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000715 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000716 QualType ExpectedType
717 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000718 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000719
Chandler Carruthaaa1a892010-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 Gregor48026d22010-01-11 18:40:55 +0000727 }
728 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000729
John McCallf36e02d2009-10-09 21:13:30 +0000730 return Found;
731}
732
John McCalld7be78a2009-11-10 07:01:13 +0000733// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000734static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000735CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000736 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000737
738 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
739
John McCalld7be78a2009-11-10 07:01:13 +0000740 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000741 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000742
John McCalld7be78a2009-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 Stump1eb44332009-09-09 15:08:12 +0000747
John McCalld7be78a2009-11-10 07:01:13 +0000748 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000749 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000750 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000751
752 R.resolveKind();
753
754 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000755}
756
757static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000758 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000759 return Ctx->isFileContext();
760 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000761}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000762
Douglas Gregor711be1e2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000773 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000774 OuterS = OuterS->getParent()) {
775 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000776 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000789 // namespace N {
790 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000791 //
792 // template<class T> class B {
793 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000794 // };
Douglas Gregor711be1e2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000803 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000804 !S->getParent()->isTemplateParamScope())
805 return std::make_pair(Lexical, false);
806
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000807 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000814
Douglas Gregor711be1e2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000820
Douglas Gregor711be1e2010-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 Gregore942bbe2009-09-10 16:57:35 +0000830}
831
John McCalla24dc2e2009-11-17 02:14:36 +0000832bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000833 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000834
835 DeclarationName Name = R.getLookupName();
836
Douglas Gregora376d102010-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 Takumidfbb02a2011-01-27 07:10:08 +0000844
Douglas Gregora376d102010-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 Gregor2a3009a2009-02-03 19:21:40 +0000848 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000849 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000850 I = IdResolver.begin(Name),
851 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000852
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000853 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000854 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-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 Friedman33a31382009-08-05 19:21:58 +0000858 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000859 // indirectly".
Douglas Gregor2a3009a2009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000870 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000871 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000872 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000873 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
874
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000875 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000876 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000877 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000878 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000879 Found = true;
880 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000881 }
882 }
John McCallf36e02d2009-10-09 21:13:30 +0000883 if (Found) {
884 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000885 if (S->isClassScope())
886 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
887 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000888 return true;
889 }
890
Douglas Gregor711be1e2010-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 Gregordbdf5e72010-03-15 15:26:48 +0000909 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-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 Gregore942bbe2009-09-10 16:57:35 +0000914 continue;
Douglas Gregor36262b82010-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 Takumidfbb02a2011-01-27 07:10:08 +0000927 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-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 Gregore942bbe2009-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 Gregor7d3f5762010-01-15 01:44:47 +0000947 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000948 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000949 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000950 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000951 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000952
John McCalld7be78a2009-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 Kyrtzidis78f59112010-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 Gregor7dda67d2009-02-05 19:25:20 +0000961 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000962 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000963 //
Mike Stump390b4cc2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000966
John McCalld7be78a2009-11-10 07:01:13 +0000967 UnqualUsingDirectiveSet UDirs;
968 UDirs.visitScopeChain(Initial, S);
969 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000970
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000971 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-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 Gregor7dda67d2009-02-05 19:25:20 +0000975
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000976 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000977 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000978 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000979 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000980 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-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 McCallf36e02d2009-10-09 21:13:30 +0000985 Found = true;
986 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000987 }
988 }
989
Douglas Gregor00b4b032010-05-14 04:53:42 +0000990 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000991 R.resolveKind();
992 return true;
993 }
994
Douglas Gregor00b4b032010-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 Takumidfbb02a2011-01-27 07:10:08 +00001006
Douglas Gregor00b4b032010-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 Takumidfbb02a2011-01-27 07:10:08 +00001020
Douglas Gregor00b4b032010-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 Takumidfbb02a2011-01-27 07:10:08 +00001027
Douglas Gregor00b4b032010-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 Takumidfbb02a2011-01-27 07:10:08 +00001032
Douglas Gregor00b4b032010-05-14 04:53:42 +00001033 if (Found) {
1034 R.resolveKind();
1035 return true;
1036 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001037
Douglas Gregor00b4b032010-05-14 04:53:42 +00001038 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1039 return false;
1040 }
1041 }
1042
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001043 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001044 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001045 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001046
John McCallf36e02d2009-10-09 21:13:30 +00001047 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001048}
1049
Douglas Gregoreb11cd02009-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 Gregor3e41d602009-02-13 23:20:09 +00001074/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001075/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001076/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-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 McCalla24dc2e2009-11-17 02:14:36 +00001081bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1082 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001083 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001084
John McCalla24dc2e2009-11-17 02:14:36 +00001085 LookupNameKind NameKind = R.getLookupKind();
1086
Douglas Gregoreb11cd02009-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 McCall1d7c5282009-12-18 10:40:03 +00001090 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001091 // Find the nearest non-transparent declaration scope.
1092 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001093 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001094 static_cast<DeclContext *>(S->getEntity())
1095 ->isTransparentContext()))
1096 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001097 }
1098
John McCall1d7c5282009-12-18 10:40:03 +00001099 unsigned IDNS = R.getIdentifierNamespace();
1100
Douglas Gregoreb11cd02009-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 Gregord6f7e9d2009-02-24 20:03:32 +00001105 bool LeftStartingScope = false;
1106
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001107 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001108 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001109 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001110 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001111 if (NameKind == LookupRedeclarationWithLinkage) {
1112 // Determine whether this (or a previous) declaration is
1113 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001114 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-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 Jahanian98a54032011-07-12 17:16:56 +00001122 else if (NameKind == LookupObjCImplicitSelfParam &&
1123 !isa<ImplicitParamDecl>(*I))
1124 continue;
1125
John McCallf36e02d2009-10-09 21:13:30 +00001126 R.addDecl(*I);
1127
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001128 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001129 // If this declaration has the "overloadable" attribute, we
1130 // might have a set of overloaded functions.
1131
1132 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001133 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001134 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001135 S = S->getParent();
1136
1137 // Find the last declaration in this scope (with the same
1138 // name, naturally).
1139 IdentifierResolver::iterator LastI = I;
1140 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001141 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001142 break;
John McCallf36e02d2009-10-09 21:13:30 +00001143 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001144 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001145 }
1146
John McCallf36e02d2009-10-09 21:13:30 +00001147 R.resolveKind();
1148
1149 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001150 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001151 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001152 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001153 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001154 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001155 }
1156
1157 // If we didn't find a use of this identifier, and if the identifier
1158 // corresponds to a compiler builtin, create the decl object for the builtin
1159 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001160 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1161 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001162
Axel Naumannf8291a12011-02-24 16:47:47 +00001163 // If we didn't find a use of this identifier, the ExternalSource
1164 // may be able to handle the situation.
1165 // Note: some lookup failures are expected!
1166 // See e.g. R.isForRedeclaration().
1167 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001168}
1169
John McCall6e247262009-10-10 05:48:19 +00001170/// @brief Perform qualified name lookup in the namespaces nominated by
1171/// using directives by the given context.
1172///
1173/// C++98 [namespace.qual]p2:
1174/// Given X::m (where X is a user-declared namespace), or given ::m
1175/// (where X is the global namespace), let S be the set of all
1176/// declarations of m in X and in the transitive closure of all
1177/// namespaces nominated by using-directives in X and its used
1178/// namespaces, except that using-directives are ignored in any
1179/// namespace, including X, directly containing one or more
1180/// declarations of m. No namespace is searched more than once in
1181/// the lookup of a name. If S is the empty set, the program is
1182/// ill-formed. Otherwise, if S has exactly one member, or if the
1183/// context of the reference is a using-declaration
1184/// (namespace.udecl), S is the required set of declarations of
1185/// m. Otherwise if the use of m is not one that allows a unique
1186/// declaration to be chosen from S, the program is ill-formed.
1187/// C++98 [namespace.qual]p5:
1188/// During the lookup of a qualified namespace member name, if the
1189/// lookup finds more than one declaration of the member, and if one
1190/// declaration introduces a class name or enumeration name and the
1191/// other declarations either introduce the same object, the same
1192/// enumerator or a set of functions, the non-type name hides the
1193/// class or enumeration name if and only if the declarations are
1194/// from the same namespace; otherwise (the declarations are from
1195/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001196static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001197 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001198 assert(StartDC->isFileContext() && "start context is not a file context");
1199
1200 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1201 DeclContext::udir_iterator E = StartDC->using_directives_end();
1202
1203 if (I == E) return false;
1204
1205 // We have at least added all these contexts to the queue.
1206 llvm::DenseSet<DeclContext*> Visited;
1207 Visited.insert(StartDC);
1208
1209 // We have not yet looked into these namespaces, much less added
1210 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001211 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001212
1213 // We have already looked into the initial namespace; seed the queue
1214 // with its using-children.
1215 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001216 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001217 if (Visited.insert(ND).second)
1218 Queue.push_back(ND);
1219 }
1220
1221 // The easiest way to implement the restriction in [namespace.qual]p5
1222 // is to check whether any of the individual results found a tag
1223 // and, if so, to declare an ambiguity if the final result is not
1224 // a tag.
1225 bool FoundTag = false;
1226 bool FoundNonTag = false;
1227
John McCall7d384dd2009-11-18 07:57:50 +00001228 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001229
1230 bool Found = false;
1231 while (!Queue.empty()) {
1232 NamespaceDecl *ND = Queue.back();
1233 Queue.pop_back();
1234
1235 // We go through some convolutions here to avoid copying results
1236 // between LookupResults.
1237 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001238 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001239 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001240
1241 if (FoundDirect) {
1242 // First do any local hiding.
1243 DirectR.resolveKind();
1244
1245 // If the local result is a tag, remember that.
1246 if (DirectR.isSingleTagDecl())
1247 FoundTag = true;
1248 else
1249 FoundNonTag = true;
1250
1251 // Append the local results to the total results if necessary.
1252 if (UseLocal) {
1253 R.addAllDecls(LocalR);
1254 LocalR.clear();
1255 }
1256 }
1257
1258 // If we find names in this namespace, ignore its using directives.
1259 if (FoundDirect) {
1260 Found = true;
1261 continue;
1262 }
1263
1264 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1265 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1266 if (Visited.insert(Nom).second)
1267 Queue.push_back(Nom);
1268 }
1269 }
1270
1271 if (Found) {
1272 if (FoundTag && FoundNonTag)
1273 R.setAmbiguousQualifiedTagHiding();
1274 else
1275 R.resolveKind();
1276 }
1277
1278 return Found;
1279}
1280
Douglas Gregor8071e422010-08-15 06:18:01 +00001281/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001282static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001283 CXXBasePath &Path,
1284 void *Name) {
1285 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001286
Douglas Gregor8071e422010-08-15 06:18:01 +00001287 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1288 Path.Decls = BaseRecord->lookup(N);
1289 return Path.Decls.first != Path.Decls.second;
1290}
1291
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001292/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001293/// static members, nested types, and enumerators.
1294template<typename InputIterator>
1295static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1296 Decl *D = (*First)->getUnderlyingDecl();
1297 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1298 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001299
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001300 if (isa<CXXMethodDecl>(D)) {
1301 // Determine whether all of the methods are static.
1302 bool AllMethodsAreStatic = true;
1303 for(; First != Last; ++First) {
1304 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001305
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001306 if (!isa<CXXMethodDecl>(D)) {
1307 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1308 break;
1309 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001310
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001311 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1312 AllMethodsAreStatic = false;
1313 break;
1314 }
1315 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001316
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001317 if (AllMethodsAreStatic)
1318 return true;
1319 }
1320
1321 return false;
1322}
1323
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001324/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001325///
1326/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1327/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001328/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001329///
1330/// Different lookup criteria can find different names. For example, a
1331/// particular scope can have both a struct and a function of the same
1332/// name, and each can be found by certain lookup criteria. For more
1333/// information about lookup criteria, see the documentation for the
1334/// class LookupCriteria.
1335///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001336/// \param R captures both the lookup criteria and any lookup results found.
1337///
1338/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001339/// search. If the lookup criteria permits, name lookup may also search
1340/// in the parent contexts or (for C++ classes) base classes.
1341///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001342/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001343/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001344///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001345/// \returns true if lookup succeeded, false if it failed.
1346bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1347 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001348 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001349
John McCalla24dc2e2009-11-17 02:14:36 +00001350 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001351 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001353 // Make sure that the declaration context is complete.
1354 assert((!isa<TagDecl>(LookupCtx) ||
1355 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001356 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001357 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1358 ->isBeingDefined()) &&
1359 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001361 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001362 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001363 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001364 if (isa<CXXRecordDecl>(LookupCtx))
1365 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001366 return true;
1367 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001368
John McCall6e247262009-10-10 05:48:19 +00001369 // Don't descend into implied contexts for redeclarations.
1370 // C++98 [namespace.qual]p6:
1371 // In a declaration for a namespace member in which the
1372 // declarator-id is a qualified-id, given that the qualified-id
1373 // for the namespace member has the form
1374 // nested-name-specifier unqualified-id
1375 // the unqualified-id shall name a member of the namespace
1376 // designated by the nested-name-specifier.
1377 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001378 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001379 return false;
1380
John McCalla24dc2e2009-11-17 02:14:36 +00001381 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001382 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001383 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001384
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001385 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001386 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001387 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001388 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001389 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001390
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001391 // If we're performing qualified name lookup into a dependent class,
1392 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001393 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001394 // template instantiation time (at which point all bases will be available)
1395 // or we have to fail.
1396 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1397 LookupRec->hasAnyDependentBases()) {
1398 R.setNotFoundInCurrentInstantiation();
1399 return false;
1400 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001401
Douglas Gregor7176fff2009-01-15 00:26:24 +00001402 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001403 CXXBasePaths Paths;
1404 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001405
1406 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001407 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001408 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001409 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001410 case LookupOrdinaryName:
1411 case LookupMemberName:
1412 case LookupRedeclarationWithLinkage:
1413 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1414 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001415
Douglas Gregora8f32e02009-10-06 17:59:45 +00001416 case LookupTagName:
1417 BaseCallback = &CXXRecordDecl::FindTagMember;
1418 break;
John McCall9f54ad42009-12-10 09:41:52 +00001419
Douglas Gregor8071e422010-08-15 06:18:01 +00001420 case LookupAnyName:
1421 BaseCallback = &LookupAnyMember;
1422 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001423
John McCall9f54ad42009-12-10 09:41:52 +00001424 case LookupUsingDeclName:
1425 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001426
Douglas Gregora8f32e02009-10-06 17:59:45 +00001427 case LookupOperatorName:
1428 case LookupNamespaceName:
1429 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001430 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001431 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001432 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001433
Douglas Gregora8f32e02009-10-06 17:59:45 +00001434 case LookupNestedNameSpecifierName:
1435 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1436 break;
1437 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001438
John McCalla24dc2e2009-11-17 02:14:36 +00001439 if (!LookupRec->lookupInBases(BaseCallback,
1440 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001441 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001442
John McCall92f88312010-01-23 00:46:32 +00001443 R.setNamingClass(LookupRec);
1444
Douglas Gregor7176fff2009-01-15 00:26:24 +00001445 // C++ [class.member.lookup]p2:
1446 // [...] If the resulting set of declarations are not all from
1447 // sub-objects of the same type, or the set has a nonstatic member
1448 // and includes members from distinct sub-objects, there is an
1449 // ambiguity and the program is ill-formed. Otherwise that set is
1450 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001451 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001452 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001453 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001454
Douglas Gregora8f32e02009-10-06 17:59:45 +00001455 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001456 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001457 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001458
John McCall46460a62010-01-20 21:53:11 +00001459 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1460 // across all paths.
1461 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001462
Douglas Gregor7176fff2009-01-15 00:26:24 +00001463 // Determine whether we're looking at a distinct sub-object or not.
1464 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001465 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001466 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1467 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001468 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001469 }
1470
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001471 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001472 != Context.getCanonicalType(PathElement.Base->getType())) {
1473 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001474 // different types. If the declaration sets aren't the same, this
1475 // this lookup is ambiguous.
1476 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1477 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1478 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1479 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001480
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001481 while (FirstD != FirstPath->Decls.second &&
1482 CurrentD != Path->Decls.second) {
1483 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1484 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1485 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001486
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001487 ++FirstD;
1488 ++CurrentD;
1489 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001490
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001491 if (FirstD == FirstPath->Decls.second &&
1492 CurrentD == Path->Decls.second)
1493 continue;
1494 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001495
John McCallf36e02d2009-10-09 21:13:30 +00001496 R.setAmbiguousBaseSubobjectTypes(Paths);
1497 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001498 }
1499
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001500 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001501 // We have a different subobject of the same type.
1502
1503 // C++ [class.member.lookup]p5:
1504 // A static member, a nested type or an enumerator defined in
1505 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001506 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001507 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001508 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001509
Douglas Gregor7176fff2009-01-15 00:26:24 +00001510 // We have found a nonstatic member name in multiple, distinct
1511 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001512 R.setAmbiguousBaseSubobjects(Paths);
1513 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001514 }
1515 }
1516
1517 // Lookup in a base class succeeded; return these results.
1518
John McCallf36e02d2009-10-09 21:13:30 +00001519 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001520 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1521 NamedDecl *D = *I;
1522 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1523 D->getAccess());
1524 R.addDecl(D, AS);
1525 }
John McCallf36e02d2009-10-09 21:13:30 +00001526 R.resolveKind();
1527 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001528}
1529
1530/// @brief Performs name lookup for a name that was parsed in the
1531/// source code, and may contain a C++ scope specifier.
1532///
1533/// This routine is a convenience routine meant to be called from
1534/// contexts that receive a name and an optional C++ scope specifier
1535/// (e.g., "N::M::x"). It will then perform either qualified or
1536/// unqualified name lookup (with LookupQualifiedName or LookupName,
1537/// respectively) on the given name and return those results.
1538///
1539/// @param S The scope from which unqualified name lookup will
1540/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001541///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001542/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001543///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001544/// @param EnteringContext Indicates whether we are going to enter the
1545/// context of the scope-specifier SS (if present).
1546///
John McCallf36e02d2009-10-09 21:13:30 +00001547/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001548bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001549 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001550 if (SS && SS->isInvalid()) {
1551 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001552 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001553 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Douglas Gregor495c35d2009-08-25 22:51:20 +00001556 if (SS && SS->isSet()) {
1557 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001558 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001559 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001560 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001561 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001562
John McCalla24dc2e2009-11-17 02:14:36 +00001563 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001564 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001565 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001566
Douglas Gregor495c35d2009-08-25 22:51:20 +00001567 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001568 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001569 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001570 R.setNotFoundInCurrentInstantiation();
1571 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001572 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001573 }
1574
Mike Stump1eb44332009-09-09 15:08:12 +00001575 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001576 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001577}
1578
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001579
Douglas Gregor7176fff2009-01-15 00:26:24 +00001580/// @brief Produce a diagnostic describing the ambiguity that resulted
1581/// from name lookup.
1582///
1583/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001584///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001585/// @param Name The name of the entity that name lookup was
1586/// searching for.
1587///
1588/// @param NameLoc The location of the name within the source code.
1589///
1590/// @param LookupRange A source range that provides more
1591/// source-location information concerning the lookup itself. For
1592/// example, this range might highlight a nested-name-specifier that
1593/// precedes the name.
1594///
1595/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001596bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001597 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1598
John McCalla24dc2e2009-11-17 02:14:36 +00001599 DeclarationName Name = Result.getLookupName();
1600 SourceLocation NameLoc = Result.getNameLoc();
1601 SourceRange LookupRange = Result.getContextRange();
1602
John McCall6e247262009-10-10 05:48:19 +00001603 switch (Result.getAmbiguityKind()) {
1604 case LookupResult::AmbiguousBaseSubobjects: {
1605 CXXBasePaths *Paths = Result.getBasePaths();
1606 QualType SubobjectType = Paths->front().back().Base->getType();
1607 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1608 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1609 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001610
John McCall6e247262009-10-10 05:48:19 +00001611 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1612 while (isa<CXXMethodDecl>(*Found) &&
1613 cast<CXXMethodDecl>(*Found)->isStatic())
1614 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001615
John McCall6e247262009-10-10 05:48:19 +00001616 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001617
John McCall6e247262009-10-10 05:48:19 +00001618 return true;
1619 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001620
John McCall6e247262009-10-10 05:48:19 +00001621 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001622 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1623 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001624
John McCall6e247262009-10-10 05:48:19 +00001625 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001626 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001627 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1628 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001629 Path != PathEnd; ++Path) {
1630 Decl *D = *Path->Decls.first;
1631 if (DeclsPrinted.insert(D).second)
1632 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1633 }
1634
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001635 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001636 }
1637
John McCall6e247262009-10-10 05:48:19 +00001638 case LookupResult::AmbiguousTagHiding: {
1639 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001640
John McCall6e247262009-10-10 05:48:19 +00001641 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1642
1643 LookupResult::iterator DI, DE = Result.end();
1644 for (DI = Result.begin(); DI != DE; ++DI)
1645 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1646 TagDecls.insert(TD);
1647 Diag(TD->getLocation(), diag::note_hidden_tag);
1648 }
1649
1650 for (DI = Result.begin(); DI != DE; ++DI)
1651 if (!isa<TagDecl>(*DI))
1652 Diag((*DI)->getLocation(), diag::note_hiding_object);
1653
1654 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001655 LookupResult::Filter F = Result.makeFilter();
1656 while (F.hasNext()) {
1657 if (TagDecls.count(F.next()))
1658 F.erase();
1659 }
1660 F.done();
John McCall6e247262009-10-10 05:48:19 +00001661
1662 return true;
1663 }
1664
1665 case LookupResult::AmbiguousReference: {
1666 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001667
John McCall6e247262009-10-10 05:48:19 +00001668 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1669 for (; DI != DE; ++DI)
1670 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001671
John McCall6e247262009-10-10 05:48:19 +00001672 return true;
1673 }
1674 }
1675
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001676 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001677 return true;
1678}
Douglas Gregorfa047642009-02-04 00:32:51 +00001679
John McCallc7e04da2010-05-28 18:45:08 +00001680namespace {
1681 struct AssociatedLookup {
1682 AssociatedLookup(Sema &S,
1683 Sema::AssociatedNamespaceSet &Namespaces,
1684 Sema::AssociatedClassSet &Classes)
1685 : S(S), Namespaces(Namespaces), Classes(Classes) {
1686 }
1687
1688 Sema &S;
1689 Sema::AssociatedNamespaceSet &Namespaces;
1690 Sema::AssociatedClassSet &Classes;
1691 };
1692}
1693
Mike Stump1eb44332009-09-09 15:08:12 +00001694static void
John McCallc7e04da2010-05-28 18:45:08 +00001695addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001696
Douglas Gregor54022952010-04-30 07:08:38 +00001697static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1698 DeclContext *Ctx) {
1699 // Add the associated namespace for this class.
1700
1701 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1702 // be a locally scoped record.
1703
Sebastian Redl410c4f22010-08-31 20:53:31 +00001704 // We skip out of inline namespaces. The innermost non-inline namespace
1705 // contains all names of all its nested inline namespaces anyway, so we can
1706 // replace the entire inline namespace tree with its root.
1707 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1708 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001709 Ctx = Ctx->getParent();
1710
John McCall6ff07852009-08-07 22:18:02 +00001711 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001712 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001713}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001714
Mike Stump1eb44332009-09-09 15:08:12 +00001715// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001716// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001717static void
John McCallc7e04da2010-05-28 18:45:08 +00001718addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1719 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001720 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001721 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001722 switch (Arg.getKind()) {
1723 case TemplateArgument::Null:
1724 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Douglas Gregor69be8d62009-07-08 07:51:57 +00001726 case TemplateArgument::Type:
1727 // [...] the namespaces and classes associated with the types of the
1728 // template arguments provided for template type parameters (excluding
1729 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001730 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001731 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001732
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001733 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001734 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001735 // [...] the namespaces in which any template template arguments are
1736 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001737 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001738 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001739 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001740 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001741 DeclContext *Ctx = ClassTemplate->getDeclContext();
1742 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001743 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001744 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001745 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001746 }
1747 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001748 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001749
Douglas Gregor788cd062009-11-11 01:00:40 +00001750 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001751 case TemplateArgument::Integral:
1752 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001753 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001754 // associated namespaces. ]
1755 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Douglas Gregor69be8d62009-07-08 07:51:57 +00001757 case TemplateArgument::Pack:
1758 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1759 PEnd = Arg.pack_end();
1760 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001761 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001762 break;
1763 }
1764}
1765
Douglas Gregorfa047642009-02-04 00:32:51 +00001766// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001767// argument-dependent lookup with an argument of class type
1768// (C++ [basic.lookup.koenig]p2).
1769static void
John McCallc7e04da2010-05-28 18:45:08 +00001770addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1771 CXXRecordDecl *Class) {
1772
1773 // Just silently ignore anything whose name is __va_list_tag.
1774 if (Class->getDeclName() == Result.S.VAListTagName)
1775 return;
1776
Douglas Gregorfa047642009-02-04 00:32:51 +00001777 // C++ [basic.lookup.koenig]p2:
1778 // [...]
1779 // -- If T is a class type (including unions), its associated
1780 // classes are: the class itself; the class of which it is a
1781 // member, if any; and its direct and indirect base
1782 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001783 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001784
1785 // Add the class of which it is a member, if any.
1786 DeclContext *Ctx = Class->getDeclContext();
1787 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001788 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001789 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001790 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Douglas Gregorfa047642009-02-04 00:32:51 +00001792 // Add the class itself. If we've already seen this class, we don't
1793 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001794 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001795 return;
1796
Mike Stump1eb44332009-09-09 15:08:12 +00001797 // -- If T is a template-id, its associated namespaces and classes are
1798 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001799 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001800 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001801 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001802 // namespaces in which any template template arguments are defined; and
1803 // the classes in which any member templates used as template template
1804 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001805 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001806 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001807 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1808 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1809 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001810 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001811 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001812 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregor69be8d62009-07-08 07:51:57 +00001814 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1815 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001816 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001817 }
Mike Stump1eb44332009-09-09 15:08:12 +00001818
John McCall86ff3082010-02-04 22:26:26 +00001819 // Only recurse into base classes for complete types.
1820 if (!Class->hasDefinition()) {
1821 // FIXME: we might need to instantiate templates here
1822 return;
1823 }
1824
Douglas Gregorfa047642009-02-04 00:32:51 +00001825 // Add direct and indirect base classes along with their associated
1826 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001827 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001828 Bases.push_back(Class);
1829 while (!Bases.empty()) {
1830 // Pop this class off the stack.
1831 Class = Bases.back();
1832 Bases.pop_back();
1833
1834 // Visit the base classes.
1835 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1836 BaseEnd = Class->bases_end();
1837 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001838 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001839 // In dependent contexts, we do ADL twice, and the first time around,
1840 // the base type might be a dependent TemplateSpecializationType, or a
1841 // TemplateTypeParmType. If that happens, simply ignore it.
1842 // FIXME: If we want to support export, we probably need to add the
1843 // namespace of the template in a TemplateSpecializationType, or even
1844 // the classes and namespaces of known non-dependent arguments.
1845 if (!BaseType)
1846 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001847 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001848 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001849 // Find the associated namespace for this base class.
1850 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001851 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001852
1853 // Make sure we visit the bases of this base class.
1854 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1855 Bases.push_back(BaseDecl);
1856 }
1857 }
1858 }
1859}
1860
1861// \brief Add the associated classes and namespaces for
1862// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001863// (C++ [basic.lookup.koenig]p2).
1864static void
John McCallc7e04da2010-05-28 18:45:08 +00001865addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001866 // C++ [basic.lookup.koenig]p2:
1867 //
1868 // For each argument type T in the function call, there is a set
1869 // of zero or more associated namespaces and a set of zero or more
1870 // associated classes to be considered. The sets of namespaces and
1871 // classes is determined entirely by the types of the function
1872 // arguments (and the namespace of any template template
1873 // argument). Typedef names and using-declarations used to specify
1874 // the types do not contribute to this set. The sets of namespaces
1875 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001876
Chris Lattner5f9e2722011-07-23 10:55:15 +00001877 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001878 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1879
Douglas Gregorfa047642009-02-04 00:32:51 +00001880 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001881 switch (T->getTypeClass()) {
1882
1883#define TYPE(Class, Base)
1884#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1885#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1886#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1887#define ABSTRACT_TYPE(Class, Base)
1888#include "clang/AST/TypeNodes.def"
1889 // T is canonical. We can also ignore dependent types because
1890 // we don't need to do ADL at the definition point, but if we
1891 // wanted to implement template export (or if we find some other
1892 // use for associated classes and namespaces...) this would be
1893 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001894 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001895
John McCallfa4edcf2010-05-28 06:08:54 +00001896 // -- If T is a pointer to U or an array of U, its associated
1897 // namespaces and classes are those associated with U.
1898 case Type::Pointer:
1899 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1900 continue;
1901 case Type::ConstantArray:
1902 case Type::IncompleteArray:
1903 case Type::VariableArray:
1904 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1905 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001906
John McCallfa4edcf2010-05-28 06:08:54 +00001907 // -- If T is a fundamental type, its associated sets of
1908 // namespaces and classes are both empty.
1909 case Type::Builtin:
1910 break;
1911
1912 // -- If T is a class type (including unions), its associated
1913 // classes are: the class itself; the class of which it is a
1914 // member, if any; and its direct and indirect base
1915 // classes. Its associated namespaces are the namespaces in
1916 // which its associated classes are defined.
1917 case Type::Record: {
1918 CXXRecordDecl *Class
1919 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001920 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001921 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001922 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001923
John McCallfa4edcf2010-05-28 06:08:54 +00001924 // -- If T is an enumeration type, its associated namespace is
1925 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001926 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001927 // it has no associated class.
1928 case Type::Enum: {
1929 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001930
John McCallfa4edcf2010-05-28 06:08:54 +00001931 DeclContext *Ctx = Enum->getDeclContext();
1932 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001933 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001934
John McCallfa4edcf2010-05-28 06:08:54 +00001935 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001936 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001937
John McCallfa4edcf2010-05-28 06:08:54 +00001938 break;
1939 }
1940
1941 // -- If T is a function type, its associated namespaces and
1942 // classes are those associated with the function parameter
1943 // types and those associated with the return type.
1944 case Type::FunctionProto: {
1945 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1946 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1947 ArgEnd = Proto->arg_type_end();
1948 Arg != ArgEnd; ++Arg)
1949 Queue.push_back(Arg->getTypePtr());
1950 // fallthrough
1951 }
1952 case Type::FunctionNoProto: {
1953 const FunctionType *FnType = cast<FunctionType>(T);
1954 T = FnType->getResultType().getTypePtr();
1955 continue;
1956 }
1957
1958 // -- If T is a pointer to a member function of a class X, its
1959 // associated namespaces and classes are those associated
1960 // with the function parameter types and return type,
1961 // together with those associated with X.
1962 //
1963 // -- If T is a pointer to a data member of class X, its
1964 // associated namespaces and classes are those associated
1965 // with the member type together with those associated with
1966 // X.
1967 case Type::MemberPointer: {
1968 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1969
1970 // Queue up the class type into which this points.
1971 Queue.push_back(MemberPtr->getClass());
1972
1973 // And directly continue with the pointee type.
1974 T = MemberPtr->getPointeeType().getTypePtr();
1975 continue;
1976 }
1977
1978 // As an extension, treat this like a normal pointer.
1979 case Type::BlockPointer:
1980 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1981 continue;
1982
1983 // References aren't covered by the standard, but that's such an
1984 // obvious defect that we cover them anyway.
1985 case Type::LValueReference:
1986 case Type::RValueReference:
1987 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1988 continue;
1989
1990 // These are fundamental types.
1991 case Type::Vector:
1992 case Type::ExtVector:
1993 case Type::Complex:
1994 break;
1995
Douglas Gregorf25760e2011-04-12 01:02:45 +00001996 // If T is an Objective-C object or interface type, or a pointer to an
1997 // object or interface type, the associated namespace is the global
1998 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00001999 case Type::ObjCObject:
2000 case Type::ObjCInterface:
2001 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002002 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002003 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002004
2005 // Atomic types are just wrappers; use the associations of the
2006 // contained type.
2007 case Type::Atomic:
2008 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2009 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002010 }
2011
2012 if (Queue.empty()) break;
2013 T = Queue.back();
2014 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002015 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002016}
2017
2018/// \brief Find the associated classes and namespaces for
2019/// argument-dependent lookup for a call with the given set of
2020/// arguments.
2021///
2022/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002023/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002024/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002025void
Douglas Gregorfa047642009-02-04 00:32:51 +00002026Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2027 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002028 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002029 AssociatedNamespaces.clear();
2030 AssociatedClasses.clear();
2031
John McCallc7e04da2010-05-28 18:45:08 +00002032 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2033
Douglas Gregorfa047642009-02-04 00:32:51 +00002034 // C++ [basic.lookup.koenig]p2:
2035 // For each argument type T in the function call, there is a set
2036 // of zero or more associated namespaces and a set of zero or more
2037 // associated classes to be considered. The sets of namespaces and
2038 // classes is determined entirely by the types of the function
2039 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002040 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00002041 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2042 Expr *Arg = Args[ArgIdx];
2043
2044 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002045 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002046 continue;
2047 }
2048
2049 // [...] In addition, if the argument is the name or address of a
2050 // set of overloaded functions and/or function templates, its
2051 // associated classes and namespaces are the union of those
2052 // associated with each of the members of the set: the namespace
2053 // in which the function or function template is defined and the
2054 // classes and namespaces associated with its (non-dependent)
2055 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002056 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002057 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002058 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002059 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002060
John McCallc7e04da2010-05-28 18:45:08 +00002061 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2062 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002063
John McCallc7e04da2010-05-28 18:45:08 +00002064 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2065 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002066 // Look through any using declarations to find the underlying function.
2067 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002068
Chandler Carruthbd647292009-12-29 06:17:27 +00002069 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2070 if (!FDecl)
2071 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002072
2073 // Add the classes and namespaces associated with the parameter
2074 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002075 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002076 }
2077 }
2078}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002079
2080/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2081/// an acceptable non-member overloaded operator for a call whose
2082/// arguments have types T1 (and, if non-empty, T2). This routine
2083/// implements the check in C++ [over.match.oper]p3b2 concerning
2084/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002085static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002086IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2087 QualType T1, QualType T2,
2088 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002089 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2090 return true;
2091
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002092 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2093 return true;
2094
John McCall183700f2009-09-21 23:43:11 +00002095 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002096 if (Proto->getNumArgs() < 1)
2097 return false;
2098
2099 if (T1->isEnumeralType()) {
2100 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002101 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002102 return true;
2103 }
2104
2105 if (Proto->getNumArgs() < 2)
2106 return false;
2107
2108 if (!T2.isNull() && T2->isEnumeralType()) {
2109 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002110 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002111 return true;
2112 }
2113
2114 return false;
2115}
2116
John McCall7d384dd2009-11-18 07:57:50 +00002117NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002118 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002119 LookupNameKind NameKind,
2120 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002121 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002122 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002123 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002124}
2125
Douglas Gregor6e378de2009-04-23 23:18:26 +00002126/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002127ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002128 SourceLocation IdLoc) {
2129 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2130 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002131 return cast_or_null<ObjCProtocolDecl>(D);
2132}
2133
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002134void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002135 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002136 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002137 // C++ [over.match.oper]p3:
2138 // -- The set of non-member candidates is the result of the
2139 // unqualified lookup of operator@ in the context of the
2140 // expression according to the usual rules for name lookup in
2141 // unqualified function calls (3.4.2) except that all member
2142 // functions are ignored. However, if no operand has a class
2143 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002144 // that have a first parameter of type T1 or "reference to
2145 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002146 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002147 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002148 // when T2 is an enumeration type, are candidate functions.
2149 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002150 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2151 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002153 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2154
John McCallf36e02d2009-10-09 21:13:30 +00002155 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002156 return;
2157
2158 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2159 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002160 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2161 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002162 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002163 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002164 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002165 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002166 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002167 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002168 // later?
2169 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002170 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002171 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002172 }
2173}
2174
Sean Huntc39b6bc2011-06-24 02:11:39 +00002175Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002176 CXXSpecialMember SM,
2177 bool ConstArg,
2178 bool VolatileArg,
2179 bool RValueThis,
2180 bool ConstThis,
2181 bool VolatileThis) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002182 RD = RD->getDefinition();
2183 assert((RD && !RD->isBeingDefined()) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002184 "doing special member lookup into record that isn't fully complete");
2185 if (RValueThis || ConstThis || VolatileThis)
2186 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2187 "constructors and destructors always have unqualified lvalue this");
2188 if (ConstArg || VolatileArg)
2189 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2190 "parameter-less special members can't have qualified arguments");
2191
2192 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002193 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002194 ID.AddInteger(SM);
2195 ID.AddInteger(ConstArg);
2196 ID.AddInteger(VolatileArg);
2197 ID.AddInteger(RValueThis);
2198 ID.AddInteger(ConstThis);
2199 ID.AddInteger(VolatileThis);
2200
2201 void *InsertPoint;
2202 SpecialMemberOverloadResult *Result =
2203 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2204
2205 // This was already cached
2206 if (Result)
2207 return Result;
2208
Sean Hunt30543582011-06-07 00:11:58 +00002209 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2210 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002211 SpecialMemberCache.InsertNode(Result, InsertPoint);
2212
2213 if (SM == CXXDestructor) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002214 if (!RD->hasDeclaredDestructor())
2215 DeclareImplicitDestructor(RD);
2216 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002217 assert(DD && "record without a destructor");
2218 Result->setMethod(DD);
2219 Result->setSuccess(DD->isDeleted());
2220 Result->setConstParamMatch(false);
2221 return Result;
2222 }
2223
Sean Huntb320e0c2011-06-10 03:50:41 +00002224 // Prepare for overload resolution. Here we construct a synthetic argument
2225 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002226 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002227 DeclarationName Name;
2228 Expr *Arg = 0;
2229 unsigned NumArgs;
2230
2231 if (SM == CXXDefaultConstructor) {
2232 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2233 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002234 if (RD->needsImplicitDefaultConstructor())
2235 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002236 } else {
2237 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2238 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002239 if (!RD->hasDeclaredCopyConstructor())
2240 DeclareImplicitCopyConstructor(RD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002241 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2242 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002243 } else {
2244 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002245 if (!RD->hasDeclaredCopyAssignment())
2246 DeclareImplicitCopyAssignment(RD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002247 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2248 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002249 }
2250
2251 QualType ArgType = CanTy;
2252 if (ConstArg)
2253 ArgType.addConst();
2254 if (VolatileArg)
2255 ArgType.addVolatile();
2256
2257 // This isn't /really/ specified by the standard, but it's implied
2258 // we should be working from an RValue in the case of move to ensure
2259 // that we prefer to bind to rvalue references, and an LValue in the
2260 // case of copy to ensure we don't bind to rvalue references.
2261 // Possibly an XValue is actually correct in the case of move, but
2262 // there is no semantic difference for class types in this restricted
2263 // case.
2264 ExprValueKind VK;
Sean Huntab183df2011-06-22 22:13:13 +00002265 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002266 VK = VK_LValue;
2267 else
2268 VK = VK_RValue;
2269
2270 NumArgs = 1;
2271 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2272 }
2273
2274 // Create the object argument
2275 QualType ThisTy = CanTy;
2276 if (ConstThis)
2277 ThisTy.addConst();
2278 if (VolatileThis)
2279 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002280 Expr::Classification Classification =
Sean Huntb320e0c2011-06-10 03:50:41 +00002281 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2282 RValueThis ? VK_RValue : VK_LValue))->
2283 Classify(Context);
2284
2285 // Now we perform lookup on the name we computed earlier and do overload
2286 // resolution. Lookup is only performed directly into the class since there
2287 // will always be a (possibly implicit) declaration to shadow any others.
2288 OverloadCandidateSet OCS((SourceLocation()));
2289 DeclContext::lookup_iterator I, E;
2290 Result->setConstParamMatch(false);
2291
Sean Huntc39b6bc2011-06-24 02:11:39 +00002292 llvm::tie(I, E) = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002293 assert((I != E) &&
2294 "lookup for a constructor or assignment operator was empty");
2295 for ( ; I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002296 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002297
Sean Huntc39b6bc2011-06-24 02:11:39 +00002298 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002299 continue;
2300
Sean Huntc39b6bc2011-06-24 02:11:39 +00002301 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2302 // FIXME: [namespace.udecl]p15 says that we should only consider a
2303 // using declaration here if it does not match a declaration in the
2304 // derived class. We do not implement this correctly in other cases
2305 // either.
2306 Cand = U->getTargetDecl();
2307
2308 if (Cand->isInvalidDecl())
2309 continue;
2310 }
2311
2312 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002313 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002314 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002315 Classification, &Arg, NumArgs, OCS, true);
2316 else
2317 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2318 NumArgs, OCS, true);
Sean Huntb320e0c2011-06-10 03:50:41 +00002319
2320 // Here we're looking for a const parameter to speed up creation of
2321 // implicit copy methods.
2322 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2323 (SM == CXXCopyConstructor &&
2324 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2325 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Sean Hunt661c67a2011-06-21 23:42:56 +00002326 if (!ArgType->isReferenceType() ||
2327 ArgType->getPointeeType().isConstQualified())
Sean Huntb320e0c2011-06-10 03:50:41 +00002328 Result->setConstParamMatch(true);
2329 }
Sean Hunt431a1cb2011-06-22 02:58:46 +00002330 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002331 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002332 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2333 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Sean Huntc39b6bc2011-06-24 02:11:39 +00002334 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002335 OCS, true);
2336 else
2337 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2338 0, &Arg, NumArgs, OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002339 } else {
2340 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002341 }
2342 }
2343
2344 OverloadCandidateSet::iterator Best;
2345 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2346 case OR_Success:
2347 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2348 Result->setSuccess(true);
2349 break;
2350
2351 case OR_Deleted:
2352 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2353 Result->setSuccess(false);
2354 break;
2355
2356 case OR_Ambiguous:
2357 case OR_No_Viable_Function:
2358 Result->setMethod(0);
2359 Result->setSuccess(false);
2360 break;
2361 }
2362
2363 return Result;
2364}
2365
2366/// \brief Look up the default constructor for the given class.
2367CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002368 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002369 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2370 false, false);
2371
2372 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002373}
2374
Sean Hunt661c67a2011-06-21 23:42:56 +00002375/// \brief Look up the copying constructor for the given class.
2376CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2377 unsigned Quals,
2378 bool *ConstParamMatch) {
Sean Huntc530d172011-06-10 04:44:37 +00002379 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2380 "non-const, non-volatile qualifiers for copy ctor arg");
2381 SpecialMemberOverloadResult *Result =
2382 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2383 Quals & Qualifiers::Volatile, false, false, false);
2384
2385 if (ConstParamMatch)
2386 *ConstParamMatch = Result->hasConstParamMatch();
2387
2388 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2389}
2390
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002391/// \brief Look up the moving constructor for the given class.
2392CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2393 SpecialMemberOverloadResult *Result =
2394 LookupSpecialMember(Class, CXXMoveConstructor, false,
2395 false, false, false, false);
2396
2397 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2398}
2399
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002400/// \brief Look up the constructors for the given class.
2401DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002402 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002403 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002404 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002405 DeclareImplicitDefaultConstructor(Class);
2406 if (!Class->hasDeclaredCopyConstructor())
2407 DeclareImplicitCopyConstructor(Class);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002408 if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2409 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002410 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002411
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002412 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2413 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2414 return Class->lookup(Name);
2415}
2416
Sean Hunt661c67a2011-06-21 23:42:56 +00002417/// \brief Look up the copying assignment operator for the given class.
2418CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2419 unsigned Quals, bool RValueThis,
2420 unsigned ThisQuals,
2421 bool *ConstParamMatch) {
2422 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2423 "non-const, non-volatile qualifiers for copy assignment arg");
2424 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2425 "non-const, non-volatile qualifiers for copy assignment this");
2426 SpecialMemberOverloadResult *Result =
2427 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2428 Quals & Qualifiers::Volatile, RValueThis,
2429 ThisQuals & Qualifiers::Const,
2430 ThisQuals & Qualifiers::Volatile);
2431
2432 if (ConstParamMatch)
2433 *ConstParamMatch = Result->hasConstParamMatch();
2434
2435 return Result->getMethod();
2436}
2437
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002438/// \brief Look up the moving assignment operator for the given class.
2439CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2440 bool RValueThis,
2441 unsigned ThisQuals) {
2442 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2443 "non-const, non-volatile qualifiers for copy assignment this");
2444 SpecialMemberOverloadResult *Result =
2445 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2446 ThisQuals & Qualifiers::Const,
2447 ThisQuals & Qualifiers::Volatile);
2448
2449 return Result->getMethod();
2450}
2451
Douglas Gregordb89f282010-07-01 22:47:18 +00002452/// \brief Look for the destructor of the given class.
2453///
Sean Huntc5c9b532011-06-03 21:10:40 +00002454/// During semantic analysis, this routine should be used in lieu of
2455/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002456///
2457/// \returns The destructor for this class.
2458CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002459 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2460 false, false, false,
2461 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002462}
2463
John McCall7edb5fd2010-01-26 07:16:45 +00002464void ADLResult::insert(NamedDecl *New) {
2465 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2466
2467 // If we haven't yet seen a decl for this key, or the last decl
2468 // was exactly this one, we're done.
2469 if (Old == 0 || Old == New) {
2470 Old = New;
2471 return;
2472 }
2473
2474 // Otherwise, decide which is a more recent redeclaration.
2475 FunctionDecl *OldFD, *NewFD;
2476 if (isa<FunctionTemplateDecl>(New)) {
2477 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2478 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2479 } else {
2480 OldFD = cast<FunctionDecl>(Old);
2481 NewFD = cast<FunctionDecl>(New);
2482 }
2483
2484 FunctionDecl *Cursor = NewFD;
2485 while (true) {
2486 Cursor = Cursor->getPreviousDeclaration();
2487
2488 // If we got to the end without finding OldFD, OldFD is the newer
2489 // declaration; leave things as they are.
2490 if (!Cursor) return;
2491
2492 // If we do find OldFD, then NewFD is newer.
2493 if (Cursor == OldFD) break;
2494
2495 // Otherwise, keep looking.
2496 }
2497
2498 Old = New;
2499}
2500
Sebastian Redl644be852009-10-23 19:23:15 +00002501void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002502 Expr **Args, unsigned NumArgs,
Richard Smithad762fc2011-04-14 22:09:26 +00002503 ADLResult &Result,
2504 bool StdNamespaceIsAssociated) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002505 // Find all of the associated namespaces and classes based on the
2506 // arguments we have.
2507 AssociatedNamespaceSet AssociatedNamespaces;
2508 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002509 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002510 AssociatedNamespaces,
2511 AssociatedClasses);
Richard Smithad762fc2011-04-14 22:09:26 +00002512 if (StdNamespaceIsAssociated && StdNamespace)
2513 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002514
Sebastian Redl644be852009-10-23 19:23:15 +00002515 QualType T1, T2;
2516 if (Operator) {
2517 T1 = Args[0]->getType();
2518 if (NumArgs >= 2)
2519 T2 = Args[1]->getType();
2520 }
2521
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002522 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002523 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2524 // and let Y be the lookup set produced by argument dependent
2525 // lookup (defined as follows). If X contains [...] then Y is
2526 // empty. Otherwise Y is the set of declarations found in the
2527 // namespaces associated with the argument types as described
2528 // below. The set of declarations found by the lookup of the name
2529 // is the union of X and Y.
2530 //
2531 // Here, we compute Y and add its members to the overloaded
2532 // candidate set.
2533 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002534 NSEnd = AssociatedNamespaces.end();
2535 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002536 // When considering an associated namespace, the lookup is the
2537 // same as the lookup performed when the associated namespace is
2538 // used as a qualifier (3.4.3.2) except that:
2539 //
2540 // -- Any using-directives in the associated namespace are
2541 // ignored.
2542 //
John McCall6ff07852009-08-07 22:18:02 +00002543 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002544 // associated classes are visible within their respective
2545 // namespaces even if they are not visible during an ordinary
2546 // lookup (11.4).
2547 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002548 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002549 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002550 // If the only declaration here is an ordinary friend, consider
2551 // it only if it was declared in an associated classes.
2552 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002553 DeclContext *LexDC = D->getLexicalDeclContext();
2554 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2555 continue;
2556 }
Mike Stump1eb44332009-09-09 15:08:12 +00002557
John McCalla113e722010-01-26 06:04:06 +00002558 if (isa<UsingShadowDecl>(D))
2559 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002560
John McCalla113e722010-01-26 06:04:06 +00002561 if (isa<FunctionDecl>(D)) {
2562 if (Operator &&
2563 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2564 T1, T2, Context))
2565 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002566 } else if (!isa<FunctionTemplateDecl>(D))
2567 continue;
2568
2569 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002570 }
2571 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002572}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002573
2574//----------------------------------------------------------------------------
2575// Search for all visible declarations.
2576//----------------------------------------------------------------------------
2577VisibleDeclConsumer::~VisibleDeclConsumer() { }
2578
2579namespace {
2580
2581class ShadowContextRAII;
2582
2583class VisibleDeclsRecord {
2584public:
2585 /// \brief An entry in the shadow map, which is optimized to store a
2586 /// single declaration (the common case) but can also store a list
2587 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002588 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002589
2590private:
2591 /// \brief A mapping from declaration names to the declarations that have
2592 /// this name within a particular scope.
2593 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2594
2595 /// \brief A list of shadow maps, which is used to model name hiding.
2596 std::list<ShadowMap> ShadowMaps;
2597
2598 /// \brief The declaration contexts we have already visited.
2599 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2600
2601 friend class ShadowContextRAII;
2602
2603public:
2604 /// \brief Determine whether we have already visited this context
2605 /// (and, if not, note that we are going to visit that context now).
2606 bool visitedContext(DeclContext *Ctx) {
2607 return !VisitedContexts.insert(Ctx);
2608 }
2609
Douglas Gregor8071e422010-08-15 06:18:01 +00002610 bool alreadyVisitedContext(DeclContext *Ctx) {
2611 return VisitedContexts.count(Ctx);
2612 }
2613
Douglas Gregor546be3c2009-12-30 17:04:44 +00002614 /// \brief Determine whether the given declaration is hidden in the
2615 /// current scope.
2616 ///
2617 /// \returns the declaration that hides the given declaration, or
2618 /// NULL if no such declaration exists.
2619 NamedDecl *checkHidden(NamedDecl *ND);
2620
2621 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002622 void add(NamedDecl *ND) {
2623 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2624 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002625};
2626
2627/// \brief RAII object that records when we've entered a shadow context.
2628class ShadowContextRAII {
2629 VisibleDeclsRecord &Visible;
2630
2631 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2632
2633public:
2634 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2635 Visible.ShadowMaps.push_back(ShadowMap());
2636 }
2637
2638 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002639 Visible.ShadowMaps.pop_back();
2640 }
2641};
2642
2643} // end anonymous namespace
2644
Douglas Gregor546be3c2009-12-30 17:04:44 +00002645NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002646 // Look through using declarations.
2647 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002648
Douglas Gregor546be3c2009-12-30 17:04:44 +00002649 unsigned IDNS = ND->getIdentifierNamespace();
2650 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2651 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2652 SM != SMEnd; ++SM) {
2653 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2654 if (Pos == SM->end())
2655 continue;
2656
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002657 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002658 IEnd = Pos->second.end();
2659 I != IEnd; ++I) {
2660 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002661 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002662 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002663 Decl::IDNS_ObjCProtocol)))
2664 continue;
2665
2666 // Protocols are in distinct namespaces from everything else.
2667 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2668 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2669 (*I)->getIdentifierNamespace() != IDNS)
2670 continue;
2671
Douglas Gregor0cc84042010-01-14 15:47:35 +00002672 // Functions and function templates in the same scope overload
2673 // rather than hide. FIXME: Look for hiding based on function
2674 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002675 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002676 ND->isFunctionOrFunctionTemplate() &&
2677 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002678 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002679
Douglas Gregor546be3c2009-12-30 17:04:44 +00002680 // We've found a declaration that hides this one.
2681 return *I;
2682 }
2683 }
2684
2685 return 0;
2686}
2687
2688static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2689 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002690 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002691 VisibleDeclConsumer &Consumer,
2692 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002693 if (!Ctx)
2694 return;
2695
Douglas Gregor546be3c2009-12-30 17:04:44 +00002696 // Make sure we don't visit the same context twice.
2697 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2698 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699
Douglas Gregor4923aa22010-07-02 20:37:36 +00002700 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2701 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2702
Douglas Gregor546be3c2009-12-30 17:04:44 +00002703 // Enumerate all of the results in this context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002704 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002705 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002706 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002707 DEnd = CurCtx->decls_end();
2708 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002709 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002710 if (Result.isAcceptableDecl(ND)) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002711 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002712 Visited.add(ND);
2713 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002714 } else if (ObjCForwardProtocolDecl *ForwardProto
2715 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2716 for (ObjCForwardProtocolDecl::protocol_iterator
2717 P = ForwardProto->protocol_begin(),
2718 PEnd = ForwardProto->protocol_end();
2719 P != PEnd;
2720 ++P) {
2721 if (Result.isAcceptableDecl(*P)) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002722 Consumer.FoundDecl(*P, Visited.checkHidden(*P), Ctx, InBaseClass);
Douglas Gregor70c23352010-12-09 21:44:02 +00002723 Visited.add(*P);
2724 }
2725 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002726 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00002727 ObjCInterfaceDecl *IFace = Class->getForwardInterfaceDecl();
Douglas Gregord98abd82011-02-16 01:39:26 +00002728 if (Result.isAcceptableDecl(IFace)) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002729 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), Ctx,
2730 InBaseClass);
Douglas Gregord98abd82011-02-16 01:39:26 +00002731 Visited.add(IFace);
2732 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002733 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002734
Sebastian Redl410c4f22010-08-31 20:53:31 +00002735 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002736 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002737 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002738 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002739 Consumer, Visited);
2740 }
2741 }
2742 }
2743
2744 // Traverse using directives for qualified name lookup.
2745 if (QualifiedNameLookup) {
2746 ShadowContextRAII Shadow(Visited);
2747 DeclContext::udir_iterator I, E;
2748 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002749 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002750 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002751 }
2752 }
2753
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002754 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002755 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002756 if (!Record->hasDefinition())
2757 return;
2758
Douglas Gregor546be3c2009-12-30 17:04:44 +00002759 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2760 BEnd = Record->bases_end();
2761 B != BEnd; ++B) {
2762 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002763
Douglas Gregor546be3c2009-12-30 17:04:44 +00002764 // Don't look into dependent bases, because name lookup can't look
2765 // there anyway.
2766 if (BaseType->isDependentType())
2767 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002768
Douglas Gregor546be3c2009-12-30 17:04:44 +00002769 const RecordType *Record = BaseType->getAs<RecordType>();
2770 if (!Record)
2771 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002772
Douglas Gregor546be3c2009-12-30 17:04:44 +00002773 // FIXME: It would be nice to be able to determine whether referencing
2774 // a particular member would be ambiguous. For example, given
2775 //
2776 // struct A { int member; };
2777 // struct B { int member; };
2778 // struct C : A, B { };
2779 //
2780 // void f(C *c) { c->### }
2781 //
2782 // accessing 'member' would result in an ambiguity. However, we
2783 // could be smart enough to qualify the member with the base
2784 // class, e.g.,
2785 //
2786 // c->B::member
2787 //
2788 // or
2789 //
2790 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002791
Douglas Gregor546be3c2009-12-30 17:04:44 +00002792 // Find results in this base class (and its bases).
2793 ShadowContextRAII Shadow(Visited);
2794 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002795 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002796 }
2797 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002798
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002799 // Traverse the contexts of Objective-C classes.
2800 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2801 // Traverse categories.
2802 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2803 Category; Category = Category->getNextClassCategory()) {
2804 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002805 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002806 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002807 }
2808
2809 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002810 for (ObjCInterfaceDecl::all_protocol_iterator
2811 I = IFace->all_referenced_protocol_begin(),
2812 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002813 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002814 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002815 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002816 }
2817
2818 // Traverse the superclass.
2819 if (IFace->getSuperClass()) {
2820 ShadowContextRAII Shadow(Visited);
2821 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002822 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002823 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002824
Douglas Gregorc220a182010-04-19 18:02:19 +00002825 // If there is an implementation, traverse it. We do this to find
2826 // synthesized ivars.
2827 if (IFace->getImplementation()) {
2828 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002829 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002830 QualifiedNameLookup, true, Consumer, Visited);
2831 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002832 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2833 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2834 E = Protocol->protocol_end(); I != E; ++I) {
2835 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002836 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002837 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002838 }
2839 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2840 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2841 E = Category->protocol_end(); I != E; ++I) {
2842 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002843 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002844 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002845 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002846
Douglas Gregorc220a182010-04-19 18:02:19 +00002847 // If there is an implementation, traverse it.
2848 if (Category->getImplementation()) {
2849 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002850 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002851 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002852 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002853 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002854}
2855
2856static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2857 UnqualUsingDirectiveSet &UDirs,
2858 VisibleDeclConsumer &Consumer,
2859 VisibleDeclsRecord &Visited) {
2860 if (!S)
2861 return;
2862
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002863 if (!S->getEntity() ||
2864 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002865 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002866 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2867 // Walk through the declarations in this Scope.
2868 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2869 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002870 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002871 if (Result.isAcceptableDecl(ND)) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002872 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002873 Visited.add(ND);
2874 }
2875 }
2876 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002877
Douglas Gregor711be1e2010-03-15 14:33:29 +00002878 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002879 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002880 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002881 // Look into this scope's declaration context, along with any of its
2882 // parent lookup contexts (e.g., enclosing classes), up to the point
2883 // where we hit the context stored in the next outer scope.
2884 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002885 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002886
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002887 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002888 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002889 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2890 if (Method->isInstanceMethod()) {
2891 // For instance methods, look for ivars in the method's interface.
2892 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2893 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002894 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002895 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00002896 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00002897 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002898 }
2899
2900 // We've already performed all of the name lookup that we need
2901 // to for Objective-C methods; the next context will be the
2902 // outer scope.
2903 break;
2904 }
2905
Douglas Gregor546be3c2009-12-30 17:04:44 +00002906 if (Ctx->isFunctionOrMethod())
2907 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002908
2909 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002910 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002911 }
2912 } else if (!S->getParent()) {
2913 // Look into the translation unit scope. We walk through the translation
2914 // unit's declaration context, because the Scope itself won't have all of
2915 // the declarations if we loaded a precompiled header.
2916 // FIXME: We would like the translation unit's Scope object to point to the
2917 // translation unit, so we don't need this special "if" branch. However,
2918 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002919 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002920 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002921 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002922 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002923 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002924 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002925 }
2926
Douglas Gregor546be3c2009-12-30 17:04:44 +00002927 if (Entity) {
2928 // Lookup visible declarations in any namespaces found by using
2929 // directives.
2930 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2931 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2932 for (; UI != UEnd; ++UI)
2933 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002934 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002935 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002936 }
2937
2938 // Lookup names in the parent scope.
2939 ShadowContextRAII Shadow(Visited);
2940 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2941}
2942
2943void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002944 VisibleDeclConsumer &Consumer,
2945 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002946 // Determine the set of using directives available during
2947 // unqualified name lookup.
2948 Scope *Initial = S;
2949 UnqualUsingDirectiveSet UDirs;
2950 if (getLangOptions().CPlusPlus) {
2951 // Find the first namespace or translation-unit scope.
2952 while (S && !isNamespaceOrTranslationUnitScope(S))
2953 S = S->getParent();
2954
2955 UDirs.visitScopeChain(Initial, S);
2956 }
2957 UDirs.done();
2958
2959 // Look for visible declarations.
2960 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2961 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002962 if (!IncludeGlobalScope)
2963 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002964 ShadowContextRAII Shadow(Visited);
2965 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2966}
2967
2968void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002969 VisibleDeclConsumer &Consumer,
2970 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002971 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2972 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002973 if (!IncludeGlobalScope)
2974 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002975 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002976 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002977 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002978}
2979
Chris Lattner4ae493c2011-02-18 02:08:43 +00002980/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00002981/// If GnuLabelLoc is a valid source location, then this is a definition
2982/// of an __label__ label name, otherwise it is a normal label definition
2983/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00002984LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00002985 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00002986 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00002987 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00002988
2989 if (GnuLabelLoc.isValid()) {
2990 // Local label definitions always shadow existing labels.
2991 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
2992 Scope *S = CurScope;
2993 PushOnScopeChains(Res, S, true);
2994 return cast<LabelDecl>(Res);
2995 }
2996
2997 // Not a GNU local label.
2998 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
2999 // If we found a label, check to see if it is in the same context as us.
3000 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003001 if (Res && Res->getDeclContext() != CurContext)
3002 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003003 if (Res == 0) {
3004 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003005 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3006 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003007 assert(S && "Not in a function?");
3008 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003009 }
Chris Lattner337e5502011-02-18 01:27:55 +00003010 return cast<LabelDecl>(Res);
3011}
3012
3013//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003014// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003015//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003016
3017namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003018
3019typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003020typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003021
3022static const unsigned MaxTypoDistanceResultSets = 5;
3023
Douglas Gregor546be3c2009-12-30 17:04:44 +00003024class TypoCorrectionConsumer : public VisibleDeclConsumer {
3025 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003026 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003027
3028 /// \brief The results found that have the smallest edit distance
3029 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003030 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003031 /// The pointer value being set to the current DeclContext indicates
3032 /// whether there is a keyword with this name.
3033 TypoEditDistanceMap BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003034
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003035 /// \brief The worst of the best N edit distances found so far.
3036 unsigned MaxEditDistance;
3037
3038 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003039
Douglas Gregor546be3c2009-12-30 17:04:44 +00003040public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003041 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003042 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003043 MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3044 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003045
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003046 ~TypoCorrectionConsumer() {
3047 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3048 IEnd = BestResults.end();
3049 I != IEnd;
3050 ++I)
3051 delete I->second;
3052 }
3053
Erik Verbruggend1205962011-10-06 07:27:49 +00003054 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3055 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003056 void FoundName(StringRef Name);
3057 void addKeywordResult(StringRef Keyword);
3058 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003059 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003060 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003061
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003062 typedef TypoResultsMap::iterator result_iterator;
3063 typedef TypoEditDistanceMap::iterator distance_iterator;
3064 distance_iterator begin() { return BestResults.begin(); }
3065 distance_iterator end() { return BestResults.end(); }
3066 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregore24b5752010-10-14 20:34:08 +00003067 unsigned size() const { return BestResults.size(); }
3068 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003069
Chris Lattner5f9e2722011-07-23 10:55:15 +00003070 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003071 return (*BestResults.begin()->second)[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003072 }
3073
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003074 unsigned getMaxEditDistance() const {
3075 return MaxEditDistance;
3076 }
3077
3078 unsigned getBestEditDistance() {
3079 return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3080 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003081};
3082
3083}
3084
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003085void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003086 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003087 // Don't consider hidden names for typo correction.
3088 if (Hiding)
3089 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003090
Douglas Gregor546be3c2009-12-30 17:04:44 +00003091 // Only consider entities with identifiers for names, ignoring
3092 // special names (constructors, overloaded operators, selectors,
3093 // etc.).
3094 IdentifierInfo *Name = ND->getIdentifier();
3095 if (!Name)
3096 return;
3097
Douglas Gregor95f42922010-10-14 22:11:03 +00003098 FoundName(Name->getName());
3099}
3100
Chris Lattner5f9e2722011-07-23 10:55:15 +00003101void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003102 // Use a simple length-based heuristic to determine the minimum possible
3103 // edit distance. If the minimum isn't good enough, bail out early.
3104 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003105 if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
Douglas Gregor362a8f22010-10-19 19:39:10 +00003106 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003107
Douglas Gregora1194772010-10-19 22:14:33 +00003108 // Compute an upper bound on the allowable edit distance, so that the
3109 // edit-distance algorithm can short-circuit.
Jay Foadf1cc1d02011-04-23 09:06:00 +00003110 unsigned UpperBound =
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003111 std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112
Douglas Gregor546be3c2009-12-30 17:04:44 +00003113 // Compute the edit distance between the typo and the name of this
3114 // entity. If this edit distance is not worse than the best edit
3115 // distance we've seen so far, add it to the list of results.
Douglas Gregora1194772010-10-19 22:14:33 +00003116 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003117
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003118 if (ED > MaxEditDistance) {
Douglas Gregore24b5752010-10-14 20:34:08 +00003119 // This result is worse than the best results we've seen so far;
3120 // ignore it.
3121 return;
3122 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003123
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003124 addName(Name, NULL, ED);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003125}
3126
Chris Lattner5f9e2722011-07-23 10:55:15 +00003127void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003128 // Compute the edit distance between the typo and this keyword.
3129 // If this edit distance is not worse than the best edit
3130 // distance we've seen so far, add it to the list of results.
3131 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003132 if (ED > MaxEditDistance) {
Douglas Gregore24b5752010-10-14 20:34:08 +00003133 // This result is worse than the best results we've seen so far;
3134 // ignore it.
3135 return;
3136 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003137
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003138 addName(Keyword, NULL, ED, NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003139}
3140
Chris Lattner5f9e2722011-07-23 10:55:15 +00003141void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003142 NamedDecl *ND,
3143 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003144 NestedNameSpecifier *NNS,
3145 bool isKeyword) {
3146 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3147 if (isKeyword) TC.makeKeyword();
3148 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003149}
3150
3151void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003152 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003153 TypoResultsMap *& Map = BestResults[Correction.getEditDistance()];
3154 if (!Map)
3155 Map = new TypoResultsMap;
Chandler Carruth55620532011-06-28 22:48:40 +00003156
3157 TypoCorrection &CurrentCorrection = (*Map)[Name];
3158 if (!CurrentCorrection ||
3159 // FIXME: The following should be rolled up into an operator< on
3160 // TypoCorrection with a more principled definition.
3161 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3162 Correction.getAsString(SemaRef.getLangOptions()) <
3163 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3164 CurrentCorrection = Correction;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003165
3166 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003167 TypoEditDistanceMap::iterator Last = BestResults.end();
3168 --Last;
3169 delete Last->second;
3170 BestResults.erase(Last);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003171 }
3172}
3173
3174namespace {
3175
3176class SpecifierInfo {
3177 public:
3178 DeclContext* DeclCtx;
3179 NestedNameSpecifier* NameSpecifier;
3180 unsigned EditDistance;
3181
3182 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3183 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3184};
3185
Chris Lattner5f9e2722011-07-23 10:55:15 +00003186typedef SmallVector<DeclContext*, 4> DeclContextList;
3187typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003188
3189class NamespaceSpecifierSet {
3190 ASTContext &Context;
3191 DeclContextList CurContextChain;
3192 bool isSorted;
3193
3194 SpecifierInfoList Specifiers;
3195 llvm::SmallSetVector<unsigned, 4> Distances;
3196 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3197
3198 /// \brief Helper for building the list of DeclContexts between the current
3199 /// context and the top of the translation unit
3200 static DeclContextList BuildContextChain(DeclContext *Start);
3201
3202 void SortNamespaces();
3203
3204 public:
3205 explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003206 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3207 isSorted(true) {}
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003208
3209 /// \brief Add the namespace to the set, computing the corresponding
3210 /// NestedNameSpecifier and its distance in the process.
3211 void AddNamespace(NamespaceDecl *ND);
3212
3213 typedef SpecifierInfoList::iterator iterator;
3214 iterator begin() {
3215 if (!isSorted) SortNamespaces();
3216 return Specifiers.begin();
3217 }
3218 iterator end() { return Specifiers.end(); }
3219};
3220
3221}
3222
3223DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003224 assert(Start && "Bulding a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003225 DeclContextList Chain;
3226 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3227 DC = DC->getLookupParent()) {
3228 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3229 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3230 !(ND && ND->isAnonymousNamespace()))
3231 Chain.push_back(DC->getPrimaryContext());
3232 }
3233 return Chain;
3234}
3235
3236void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003237 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003238 sortedDistances.append(Distances.begin(), Distances.end());
3239
3240 if (sortedDistances.size() > 1)
3241 std::sort(sortedDistances.begin(), sortedDistances.end());
3242
3243 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003244 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003245 DIEnd = sortedDistances.end();
3246 DI != DIEnd; ++DI) {
3247 SpecifierInfoList &SpecList = DistanceMap[*DI];
3248 Specifiers.append(SpecList.begin(), SpecList.end());
3249 }
3250
3251 isSorted = true;
3252}
3253
3254void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003255 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003256 NestedNameSpecifier *NNS = NULL;
3257 unsigned NumSpecifiers = 0;
3258 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3259
3260 // Eliminate common elements from the two DeclContext chains
3261 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3262 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003263 C != CEnd && !NamespaceDeclChain.empty() &&
3264 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003265 NamespaceDeclChain.pop_back();
3266 }
3267
3268 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3269 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3270 CEnd = NamespaceDeclChain.rend();
3271 C != CEnd; ++C) {
3272 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3273 if (ND) {
3274 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3275 ++NumSpecifiers;
3276 }
3277 }
3278
3279 isSorted = false;
3280 Distances.insert(NumSpecifiers);
3281 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003282}
3283
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003284/// \brief Perform name lookup for a possible result for typo correction.
3285static void LookupPotentialTypoResult(Sema &SemaRef,
3286 LookupResult &Res,
3287 IdentifierInfo *Name,
3288 Scope *S, CXXScopeSpec *SS,
3289 DeclContext *MemberContext,
3290 bool EnteringContext,
3291 Sema::CorrectTypoContext CTC) {
3292 Res.suppressDiagnostics();
3293 Res.clear();
3294 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003295 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003296 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3297 if (CTC == Sema::CTC_ObjCIvarLookup) {
3298 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3299 Res.addDecl(Ivar);
3300 Res.resolveKind();
3301 return;
3302 }
3303 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003304
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003305 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3306 Res.addDecl(Prop);
3307 Res.resolveKind();
3308 return;
3309 }
3310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003311
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003312 SemaRef.LookupQualifiedName(Res, MemberContext);
3313 return;
3314 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003315
3316 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003317 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003318
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003319 // Fake ivar lookup; this should really be part of
3320 // LookupParsedName.
3321 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3322 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003323 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003324 (Res.isSingleResult() &&
3325 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003326 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003327 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3328 Res.addDecl(IV);
3329 Res.resolveKind();
3330 }
3331 }
3332 }
3333}
3334
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003335/// \brief Add keywords to the consumer as possible typo corrections.
3336static void AddKeywordsToConsumer(Sema &SemaRef,
3337 TypoCorrectionConsumer &Consumer,
3338 Scope *S, Sema::CorrectTypoContext CTC) {
3339 // Add context-dependent keywords.
3340 bool WantTypeSpecifiers = false;
3341 bool WantExpressionKeywords = false;
3342 bool WantCXXNamedCasts = false;
3343 bool WantRemainingKeywords = false;
3344 switch (CTC) {
3345 case Sema::CTC_Unknown:
3346 WantTypeSpecifiers = true;
3347 WantExpressionKeywords = true;
3348 WantCXXNamedCasts = true;
3349 WantRemainingKeywords = true;
3350
3351 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3352 if (Method->getClassInterface() &&
3353 Method->getClassInterface()->getSuperClass())
3354 Consumer.addKeywordResult("super");
3355
3356 break;
3357
3358 case Sema::CTC_NoKeywords:
3359 break;
3360
3361 case Sema::CTC_Type:
3362 WantTypeSpecifiers = true;
3363 break;
3364
3365 case Sema::CTC_ObjCMessageReceiver:
3366 Consumer.addKeywordResult("super");
3367 // Fall through to handle message receivers like expressions.
3368
3369 case Sema::CTC_Expression:
3370 if (SemaRef.getLangOptions().CPlusPlus)
3371 WantTypeSpecifiers = true;
3372 WantExpressionKeywords = true;
3373 // Fall through to get C++ named casts.
3374
3375 case Sema::CTC_CXXCasts:
3376 WantCXXNamedCasts = true;
3377 break;
3378
3379 case Sema::CTC_ObjCPropertyLookup:
3380 // FIXME: Add "isa"?
3381 break;
3382
3383 case Sema::CTC_MemberLookup:
3384 if (SemaRef.getLangOptions().CPlusPlus)
3385 Consumer.addKeywordResult("template");
3386 break;
3387
3388 case Sema::CTC_ObjCIvarLookup:
3389 break;
3390 }
3391
3392 if (WantTypeSpecifiers) {
3393 // Add type-specifier keywords to the set of results.
3394 const char *CTypeSpecs[] = {
3395 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003396 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003397 "_Complex", "_Imaginary",
3398 // storage-specifiers as well
3399 "extern", "inline", "static", "typedef"
3400 };
3401
3402 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3403 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3404 Consumer.addKeywordResult(CTypeSpecs[I]);
3405
3406 if (SemaRef.getLangOptions().C99)
3407 Consumer.addKeywordResult("restrict");
3408 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3409 Consumer.addKeywordResult("bool");
Douglas Gregor07f4a062011-07-01 21:27:45 +00003410 else if (SemaRef.getLangOptions().C99)
3411 Consumer.addKeywordResult("_Bool");
3412
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003413 if (SemaRef.getLangOptions().CPlusPlus) {
3414 Consumer.addKeywordResult("class");
3415 Consumer.addKeywordResult("typename");
3416 Consumer.addKeywordResult("wchar_t");
3417
3418 if (SemaRef.getLangOptions().CPlusPlus0x) {
3419 Consumer.addKeywordResult("char16_t");
3420 Consumer.addKeywordResult("char32_t");
3421 Consumer.addKeywordResult("constexpr");
3422 Consumer.addKeywordResult("decltype");
3423 Consumer.addKeywordResult("thread_local");
3424 }
3425 }
3426
3427 if (SemaRef.getLangOptions().GNUMode)
3428 Consumer.addKeywordResult("typeof");
3429 }
3430
3431 if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3432 Consumer.addKeywordResult("const_cast");
3433 Consumer.addKeywordResult("dynamic_cast");
3434 Consumer.addKeywordResult("reinterpret_cast");
3435 Consumer.addKeywordResult("static_cast");
3436 }
3437
3438 if (WantExpressionKeywords) {
3439 Consumer.addKeywordResult("sizeof");
3440 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3441 Consumer.addKeywordResult("false");
3442 Consumer.addKeywordResult("true");
3443 }
3444
3445 if (SemaRef.getLangOptions().CPlusPlus) {
3446 const char *CXXExprs[] = {
3447 "delete", "new", "operator", "throw", "typeid"
3448 };
3449 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3450 for (unsigned I = 0; I != NumCXXExprs; ++I)
3451 Consumer.addKeywordResult(CXXExprs[I]);
3452
3453 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3454 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3455 Consumer.addKeywordResult("this");
3456
3457 if (SemaRef.getLangOptions().CPlusPlus0x) {
3458 Consumer.addKeywordResult("alignof");
3459 Consumer.addKeywordResult("nullptr");
3460 }
3461 }
3462 }
3463
3464 if (WantRemainingKeywords) {
3465 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3466 // Statements.
3467 const char *CStmts[] = {
3468 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3469 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3470 for (unsigned I = 0; I != NumCStmts; ++I)
3471 Consumer.addKeywordResult(CStmts[I]);
3472
3473 if (SemaRef.getLangOptions().CPlusPlus) {
3474 Consumer.addKeywordResult("catch");
3475 Consumer.addKeywordResult("try");
3476 }
3477
3478 if (S && S->getBreakParent())
3479 Consumer.addKeywordResult("break");
3480
3481 if (S && S->getContinueParent())
3482 Consumer.addKeywordResult("continue");
3483
3484 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3485 Consumer.addKeywordResult("case");
3486 Consumer.addKeywordResult("default");
3487 }
3488 } else {
3489 if (SemaRef.getLangOptions().CPlusPlus) {
3490 Consumer.addKeywordResult("namespace");
3491 Consumer.addKeywordResult("template");
3492 }
3493
3494 if (S && S->isClassScope()) {
3495 Consumer.addKeywordResult("explicit");
3496 Consumer.addKeywordResult("friend");
3497 Consumer.addKeywordResult("mutable");
3498 Consumer.addKeywordResult("private");
3499 Consumer.addKeywordResult("protected");
3500 Consumer.addKeywordResult("public");
3501 Consumer.addKeywordResult("virtual");
3502 }
3503 }
3504
3505 if (SemaRef.getLangOptions().CPlusPlus) {
3506 Consumer.addKeywordResult("using");
3507
3508 if (SemaRef.getLangOptions().CPlusPlus0x)
3509 Consumer.addKeywordResult("static_assert");
3510 }
3511 }
3512}
3513
Douglas Gregor546be3c2009-12-30 17:04:44 +00003514/// \brief Try to "correct" a typo in the source code by finding
3515/// visible declarations whose names are similar to the name that was
3516/// present in the source code.
3517///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003518/// \param TypoName the \c DeclarationNameInfo structure that contains
3519/// the name that was present in the source code along with its location.
3520///
3521/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003522///
3523/// \param S the scope in which name lookup occurs.
3524///
3525/// \param SS the nested-name-specifier that precedes the name we're
3526/// looking for, if present.
3527///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003528/// \param MemberContext if non-NULL, the context in which to look for
3529/// a member access expression.
3530///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003531/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003532/// the nested-name-specifier SS.
3533///
Douglas Gregoraaf87162010-04-14 20:04:41 +00003534/// \param CTC The context in which typo correction occurs, which impacts the
3535/// set of keywords permitted.
3536///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003537/// \param OPT when non-NULL, the search for visible declarations will
3538/// also walk the protocols in the qualified interfaces of \p OPT.
3539///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003540/// \returns a \c TypoCorrection containing the corrected name if the typo
3541/// along with information such as the \c NamedDecl where the corrected name
3542/// was declared, and any additional \c NestedNameSpecifier needed to access
3543/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3544TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3545 Sema::LookupNameKind LookupKind,
3546 Scope *S, CXXScopeSpec *SS,
3547 DeclContext *MemberContext,
3548 bool EnteringContext,
3549 CorrectTypoContext CTC,
3550 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00003551 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003552 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003553
Douglas Gregor546be3c2009-12-30 17:04:44 +00003554 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003555 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003556 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003557 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003558
3559 // If the scope specifier itself was invalid, don't try to correct
3560 // typos.
3561 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003562 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003563
3564 // Never try to correct typos during template deduction or
3565 // instantiation.
3566 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003567 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003568
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003569 NamespaceSpecifierSet Namespaces(Context, CurContext);
3570
3571 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003572
Douglas Gregoraaf87162010-04-14 20:04:41 +00003573 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003574 bool IsUnqualifiedLookup = false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003575 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003576 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003577
3578 // Look in qualified interfaces.
3579 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003580 for (ObjCObjectPointerType::qual_iterator
3581 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003582 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003583 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003584 }
3585 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003586 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3587 if (!DC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003588 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003589
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003590 // Provide a stop gap for files that are just seriously broken. Trying
3591 // to correct all typos can turn into a HUGE performance penalty, causing
3592 // some files to take minutes to get rejected by the parser.
3593 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003594 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003595 ++TyposCorrected;
3596
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003597 LookupVisibleDecls(DC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003598 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003599 IsUnqualifiedLookup = true;
3600 UnqualifiedTyposCorrectedMap::iterator Cached
3601 = UnqualifiedTyposCorrected.find(Typo);
3602 if (Cached == UnqualifiedTyposCorrected.end()) {
3603 // Provide a stop gap for files that are just seriously broken. Trying
3604 // to correct all typos can turn into a HUGE performance penalty, causing
3605 // some files to take minutes to get rejected by the parser.
3606 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003607 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003608
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003609 // For unqualified lookup, look through all of the names that we have
3610 // seen in this translation unit.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003611 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003612 IEnd = Context.Idents.end();
3613 I != IEnd; ++I)
3614 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003615
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003616 // Walk through identifiers in external identifier sources.
3617 if (IdentifierInfoLookup *External
Douglas Gregor95f42922010-10-14 22:11:03 +00003618 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenek7a054b12010-11-07 06:11:33 +00003619 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003620 do {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003621 StringRef Name = Iter->Next();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003622 if (Name.empty())
3623 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003624
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003625 Consumer.FoundName(Name);
3626 } while (true);
3627 }
3628 } else {
3629 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3630 // end up adding the keyword below.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003631 if (!Cached->second)
3632 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003633
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003634 if (!Cached->second.isKeyword())
3635 Consumer.addCorrection(Cached->second);
Douglas Gregor95f42922010-10-14 22:11:03 +00003636 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003637 }
3638
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003639 AddKeywordsToConsumer(*this, Consumer, S, CTC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003640
Douglas Gregoraaf87162010-04-14 20:04:41 +00003641 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003642 if (Consumer.empty()) {
3643 // If this was an unqualified lookup, note that no correction was found.
3644 if (IsUnqualifiedLookup)
3645 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003646
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003647 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003648 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003649
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003650 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003651 // made. Otherwise, we don't even both looking at the results.
3652 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003653 if (ED > 0 && Typo->getName().size() / ED < 3) {
3654 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003655 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003656 (void)UnqualifiedTyposCorrected[Typo];
3657
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003658 return TypoCorrection();
3659 }
3660
3661 // Build the NestedNameSpecifiers for the KnownNamespaces
3662 if (getLangOptions().CPlusPlus) {
3663 // Load any externally-known namespaces.
3664 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003665 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003666 LoadedExternalKnownNamespaces = true;
3667 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3668 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3669 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3670 }
3671
3672 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3673 KNI = KnownNamespaces.begin(),
3674 KNIEnd = KnownNamespaces.end();
3675 KNI != KNIEnd; ++KNI)
3676 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003677 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003678
3679 // Weed out any names that could not be found by name lookup.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003680 llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3681 LookupResult TmpRes(*this, TypoName, LookupKind);
3682 TmpRes.suppressDiagnostics();
3683 while (!Consumer.empty()) {
3684 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3685 unsigned ED = DI->first;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003686 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3687 IEnd = DI->second->end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003688 I != IEnd; /* Increment in loop. */) {
3689 // If the item already has been looked up or is a keyword, keep it
3690 if (I->second.isResolved()) {
3691 ++I;
3692 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003694
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003695 // Perform name lookup on this name.
3696 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3697 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3698 EnteringContext, CTC);
3699
3700 switch (TmpRes.getResultKind()) {
3701 case LookupResult::NotFound:
3702 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003703 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003704 QualifiedResults.insert(Name);
3705 // We didn't find this name in our scope, or didn't like what we found;
3706 // ignore it.
3707 {
3708 TypoCorrectionConsumer::result_iterator Next = I;
3709 ++Next;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003710 DI->second->erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003711 I = Next;
3712 }
3713 break;
3714
3715 case LookupResult::Ambiguous:
3716 // We don't deal with ambiguities.
3717 return TypoCorrection();
3718
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003719 case LookupResult::FoundOverloaded: {
3720 // Store all of the Decls for overloaded symbols
3721 for (LookupResult::iterator TRD = TmpRes.begin(),
3722 TRDEnd = TmpRes.end();
3723 TRD != TRDEnd; ++TRD)
3724 I->second.addCorrectionDecl(*TRD);
3725 ++I;
3726 break;
3727 }
3728
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003729 case LookupResult::Found:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003730 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3731 ++I;
3732 break;
3733 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003734 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003735
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003736 if (DI->second->empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003737 Consumer.erase(DI);
3738 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3739 // If there are results in the closest possible bucket, stop
3740 break;
3741
3742 // Only perform the qualified lookups for C++
3743 if (getLangOptions().CPlusPlus) {
3744 TmpRes.suppressDiagnostics();
3745 for (llvm::SmallPtrSet<IdentifierInfo*,
3746 16>::iterator QRI = QualifiedResults.begin(),
3747 QRIEnd = QualifiedResults.end();
3748 QRI != QRIEnd; ++QRI) {
3749 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3750 NIEnd = Namespaces.end();
3751 NI != NIEnd; ++NI) {
3752 DeclContext *Ctx = NI->DeclCtx;
3753 unsigned QualifiedED = ED + NI->EditDistance;
3754
3755 // Stop searching once the namespaces are too far away to create
3756 // acceptable corrections for this identifier (since the namespaces
3757 // are sorted in ascending order by edit distance)
3758 if (QualifiedED > Consumer.getMaxEditDistance()) break;
3759
3760 TmpRes.clear();
3761 TmpRes.setLookupName(*QRI);
3762 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3763
3764 switch (TmpRes.getResultKind()) {
3765 case LookupResult::Found:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003766 Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3767 QualifiedED, NI->NameSpecifier);
3768 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003769 case LookupResult::FoundOverloaded: {
3770 TypoCorrection corr(&Context.Idents.get((*QRI)->getName()), NULL,
3771 NI->NameSpecifier, QualifiedED);
3772 for (LookupResult::iterator TRD = TmpRes.begin(),
3773 TRDEnd = TmpRes.end();
3774 TRD != TRDEnd; ++TRD)
3775 corr.addCorrectionDecl(*TRD);
3776 Consumer.addCorrection(corr);
3777 break;
3778 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003779 case LookupResult::NotFound:
3780 case LookupResult::NotFoundInCurrentInstantiation:
3781 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003782 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003783 break;
3784 }
3785 }
3786 }
3787 }
3788
3789 QualifiedResults.clear();
3790 }
3791
3792 // No corrections remain...
3793 if (Consumer.empty()) return TypoCorrection();
3794
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003795 TypoResultsMap &BestResults = *Consumer.begin()->second;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003796 ED = Consumer.begin()->first;
3797
3798 if (ED > 0 && Typo->getName().size() / ED < 3) {
3799 // If this was an unqualified lookup, note that no correction was found.
3800 if (IsUnqualifiedLookup)
3801 (void)UnqualifiedTyposCorrected[Typo];
3802
3803 return TypoCorrection();
3804 }
3805
3806 // If we have multiple possible corrections, eliminate the ones where we
3807 // added namespace qualifiers to try to resolve the ambiguity (and to favor
3808 // corrections without additional namespace qualifiers)
3809 if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3810 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003811 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3812 IEnd = DI->second->end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003813 I != IEnd; /* Increment in loop. */) {
3814 if (I->second.getCorrectionSpecifier() != NULL) {
3815 TypoCorrectionConsumer::result_iterator Cur = I;
3816 ++I;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003817 DI->second->erase(Cur);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003818 } else ++I;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003819 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003820 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003821
Douglas Gregore24b5752010-10-14 20:34:08 +00003822 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003823 if (BestResults.size() == 1) {
3824 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3825 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826
Douglas Gregor53e4b552010-10-26 17:18:00 +00003827 // Don't correct to a keyword that's the same as the typo; the keyword
3828 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003829 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3830
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003831 // Record the correction for unqualified lookup.
3832 if (IsUnqualifiedLookup)
3833 UnqualifiedTyposCorrected[Typo] = Result;
3834
3835 return Result;
3836 }
3837 else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3838 && BestResults["super"].isKeyword()) {
3839 // Prefer 'super' when we're completing in a message-receiver
3840 // context.
3841
3842 // Don't correct to a keyword that's the same as the typo; the keyword
3843 // wasn't actually in scope.
3844 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003845
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003846 // Record the correction for unqualified lookup.
3847 if (IsUnqualifiedLookup)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003848 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003849
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003850 return BestResults["super"];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003851 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003852
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003853 if (IsUnqualifiedLookup)
3854 (void)UnqualifiedTyposCorrected[Typo];
3855
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003856 return TypoCorrection();
3857}
3858
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003859void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
3860 if (!CDecl) return;
3861
3862 if (isKeyword())
3863 CorrectionDecls.clear();
3864
3865 CorrectionDecls.push_back(CDecl);
3866
3867 if (!CorrectionName)
3868 CorrectionName = CDecl->getDeclName();
3869}
3870
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003871std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3872 if (CorrectionNameSpec) {
3873 std::string tmpBuffer;
3874 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3875 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3876 return PrefixOStream.str() + CorrectionName.getAsString();
3877 }
3878
3879 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003880}