blob: 1e7ef549b43472cd171b54861b2a201dc2685fc7 [file] [log] [blame]
Eli Friedman56d29372008-06-07 16:52:53 +00001//===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
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 the Decl and DeclContext classes.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/DeclBase.h"
Douglas Gregor64650af2009-02-02 23:39:07 +000015#include "clang/AST/Decl.h"
Argyrios Kyrtzidisd3bb44f2008-06-09 21:05:31 +000016#include "clang/AST/DeclCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
Eli Friedman56d29372008-06-07 16:52:53 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor44b43212008-12-11 16:49:14 +000020#include "clang/AST/Type.h"
Eli Friedman56d29372008-06-07 16:52:53 +000021#include "llvm/ADT/DenseMap.h"
Chris Lattner49f28ca2009-03-05 08:00:35 +000022#include "llvm/Support/raw_ostream.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000023#include <algorithm>
Chris Lattner3daed522009-03-02 22:20:04 +000024#include <cstdio>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000025#include <functional>
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include <vector>
Eli Friedman56d29372008-06-07 16:52:53 +000027using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// Statistics
31//===----------------------------------------------------------------------===//
32
Douglas Gregor64650af2009-02-02 23:39:07 +000033#define DECL(Derived, Base) static int n##Derived##s = 0;
34#include "clang/AST/DeclNodes.def"
Eli Friedman56d29372008-06-07 16:52:53 +000035
36static bool StatSwitch = false;
37
38// This keeps track of all decl attributes. Since so few decls have attrs, we
39// keep them in a hash map instead of wasting space in the Decl class.
40typedef llvm::DenseMap<const Decl*, Attr*> DeclAttrMapTy;
41
42static DeclAttrMapTy *DeclAttrs = 0;
43
44const char *Decl::getDeclKindName() const {
45 switch (DeclKind) {
Douglas Gregor64650af2009-02-02 23:39:07 +000046 default: assert(0 && "Declaration not in DeclNodes.def!");
47#define DECL(Derived, Base) case Derived: return #Derived;
48#include "clang/AST/DeclNodes.def"
Eli Friedman56d29372008-06-07 16:52:53 +000049 }
50}
51
Steve Naroff0a473932009-01-20 19:53:53 +000052const char *DeclContext::getDeclKindName() const {
53 switch (DeclKind) {
Douglas Gregor64650af2009-02-02 23:39:07 +000054 default: assert(0 && "Declaration context not in DeclNodes.def!");
Argyrios Kyrtzidis1ad4dd72009-02-16 14:28:33 +000055#define DECL(Derived, Base) case Decl::Derived: return #Derived;
Douglas Gregor64650af2009-02-02 23:39:07 +000056#include "clang/AST/DeclNodes.def"
Steve Naroff0a473932009-01-20 19:53:53 +000057 }
58}
59
Eli Friedman56d29372008-06-07 16:52:53 +000060bool Decl::CollectingStats(bool Enable) {
61 if (Enable)
62 StatSwitch = true;
63 return StatSwitch;
64}
65
66void Decl::PrintStats() {
67 fprintf(stderr, "*** Decl Stats:\n");
Eli Friedman56d29372008-06-07 16:52:53 +000068
Douglas Gregor64650af2009-02-02 23:39:07 +000069 int totalDecls = 0;
70#define DECL(Derived, Base) totalDecls += n##Derived##s;
71#include "clang/AST/DeclNodes.def"
72 fprintf(stderr, " %d decls total.\n", totalDecls);
73
74 int totalBytes = 0;
75#define DECL(Derived, Base) \
76 if (n##Derived##s > 0) { \
77 totalBytes += (int)(n##Derived##s * sizeof(Derived##Decl)); \
78 fprintf(stderr, " %d " #Derived " decls, %d each (%d bytes)\n", \
79 n##Derived##s, (int)sizeof(Derived##Decl), \
80 (int)(n##Derived##s * sizeof(Derived##Decl))); \
81 }
82#include "clang/AST/DeclNodes.def"
Eli Friedman56d29372008-06-07 16:52:53 +000083
Douglas Gregor64650af2009-02-02 23:39:07 +000084 fprintf(stderr, "Total bytes = %d\n", totalBytes);
Eli Friedman56d29372008-06-07 16:52:53 +000085}
86
87void Decl::addDeclKind(Kind k) {
88 switch (k) {
Douglas Gregor64650af2009-02-02 23:39:07 +000089 default: assert(0 && "Declaration not in DeclNodes.def!");
90#define DECL(Derived, Base) case Derived: ++n##Derived##s; break;
91#include "clang/AST/DeclNodes.def"
Eli Friedman56d29372008-06-07 16:52:53 +000092 }
93}
94
95//===----------------------------------------------------------------------===//
Chris Lattner49f28ca2009-03-05 08:00:35 +000096// PrettyStackTraceDecl Implementation
97//===----------------------------------------------------------------------===//
98
99void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const {
100 SourceLocation TheLoc = Loc;
101 if (TheLoc.isInvalid() && TheDecl)
102 TheLoc = TheDecl->getLocation();
103
104 if (TheLoc.isValid()) {
105 TheLoc.print(OS, SM);
106 OS << ": ";
107 }
108
109 OS << Message;
110
111 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
112 OS << " '" << DN->getQualifiedNameAsString() << '\'';
113 OS << '\n';
114}
115
116//===----------------------------------------------------------------------===//
Eli Friedman56d29372008-06-07 16:52:53 +0000117// Decl Implementation
118//===----------------------------------------------------------------------===//
119
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000120void Decl::setDeclContext(DeclContext *DC) {
121 if (isOutOfSemaDC())
122 delete getMultipleDC();
123
124 DeclCtx = reinterpret_cast<uintptr_t>(DC);
125}
126
127void Decl::setLexicalDeclContext(DeclContext *DC) {
128 if (DC == getLexicalDeclContext())
129 return;
130
131 if (isInSemaDC()) {
132 MultipleDC *MDC = new MultipleDC();
133 MDC->SemanticDC = getDeclContext();
134 MDC->LexicalDC = DC;
135 DeclCtx = reinterpret_cast<uintptr_t>(MDC) | 0x1;
136 } else {
137 getMultipleDC()->LexicalDC = DC;
138 }
139}
140
Eli Friedman56d29372008-06-07 16:52:53 +0000141// Out-of-line virtual method providing a home for Decl.
142Decl::~Decl() {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000143 if (isOutOfSemaDC())
144 delete getMultipleDC();
145
Chris Lattnercc581472009-03-04 06:05:19 +0000146 assert(!HasAttrs && "attributes should have been freed by Destroy");
Eli Friedman56d29372008-06-07 16:52:53 +0000147}
148
149void Decl::addAttr(Attr *NewAttr) {
150 if (!DeclAttrs)
151 DeclAttrs = new DeclAttrMapTy();
152
153 Attr *&ExistingAttr = (*DeclAttrs)[this];
154
155 NewAttr->setNext(ExistingAttr);
156 ExistingAttr = NewAttr;
157
158 HasAttrs = true;
159}
160
161void Decl::invalidateAttrs() {
162 if (!HasAttrs) return;
163
164 HasAttrs = false;
165 (*DeclAttrs)[this] = 0;
166 DeclAttrs->erase(this);
167
168 if (DeclAttrs->empty()) {
169 delete DeclAttrs;
170 DeclAttrs = 0;
171 }
172}
173
174const Attr *Decl::getAttrs() const {
175 if (!HasAttrs)
176 return 0;
177
178 return (*DeclAttrs)[this];
179}
180
181void Decl::swapAttrs(Decl *RHS) {
182 bool HasLHSAttr = this->HasAttrs;
183 bool HasRHSAttr = RHS->HasAttrs;
184
185 // Usually, neither decl has attrs, nothing to do.
186 if (!HasLHSAttr && !HasRHSAttr) return;
187
188 // If 'this' has no attrs, swap the other way.
189 if (!HasLHSAttr)
190 return RHS->swapAttrs(this);
191
192 // Handle the case when both decls have attrs.
193 if (HasRHSAttr) {
194 std::swap((*DeclAttrs)[this], (*DeclAttrs)[RHS]);
195 return;
196 }
197
198 // Otherwise, LHS has an attr and RHS doesn't.
199 (*DeclAttrs)[RHS] = (*DeclAttrs)[this];
200 (*DeclAttrs).erase(this);
201 this->HasAttrs = false;
202 RHS->HasAttrs = true;
203}
204
205
Chris Lattnercc581472009-03-04 06:05:19 +0000206void Decl::Destroy(ASTContext &C) {
207 // Free attributes for this decl.
208 if (HasAttrs) {
209 DeclAttrMapTy::iterator it = DeclAttrs->find(this);
210 assert(it != DeclAttrs->end() && "No attrs found but HasAttrs is true!");
211
212 // release attributes.
213 it->second->Destroy(C);
214 invalidateAttrs();
215 HasAttrs = false;
216 }
217
Douglas Gregora0fc55f2009-01-13 19:47:12 +0000218#if 0
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000219 // FIXME: Once ownership is fully understood, we can enable this code
220 if (DeclContext *DC = dyn_cast<DeclContext>(this))
221 DC->decls_begin()->Destroy(C);
Eli Friedman56d29372008-06-07 16:52:53 +0000222
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000223 // Observe the unrolled recursion. By setting N->NextDeclInScope = 0x0
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000224 // within the loop, only the Destroy method for the first Decl
225 // will deallocate all of the Decls in a chain.
226
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000227 Decl* N = NextDeclInScope;
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000228
229 while (N) {
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000230 Decl* Tmp = N->NextDeclInScope;
231 N->NextDeclInScope = 0;
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000232 N->Destroy(C);
233 N = Tmp;
Eli Friedman56d29372008-06-07 16:52:53 +0000234 }
Douglas Gregora0fc55f2009-01-13 19:47:12 +0000235
Eli Friedman56d29372008-06-07 16:52:53 +0000236 this->~Decl();
Steve Naroff3e970492009-01-27 21:25:57 +0000237 C.Deallocate((void *)this);
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000238#endif
Eli Friedman56d29372008-06-07 16:52:53 +0000239}
240
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000241Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000242 Decl::Kind DK = D->getDeclKind();
243 switch(DK) {
244#define DECL_CONTEXT(Name) \
245 case Decl::Name: \
246 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
247#define DECL_CONTEXT_BASE(Name)
248#include "clang/AST/DeclNodes.def"
249 default:
250#define DECL_CONTEXT_BASE(Name) \
251 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
252 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
253#include "clang/AST/DeclNodes.def"
254 assert(false && "a decl that inherits DeclContext isn't handled");
255 return 0;
256 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000257}
258
259DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000260 Decl::Kind DK = D->getKind();
261 switch(DK) {
262#define DECL_CONTEXT(Name) \
263 case Decl::Name: \
264 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
265#define DECL_CONTEXT_BASE(Name)
266#include "clang/AST/DeclNodes.def"
267 default:
268#define DECL_CONTEXT_BASE(Name) \
269 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
270 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
271#include "clang/AST/DeclNodes.def"
272 assert(false && "a decl that inherits DeclContext isn't handled");
273 return 0;
274 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000275}
276
Eli Friedman56d29372008-06-07 16:52:53 +0000277//===----------------------------------------------------------------------===//
278// DeclContext Implementation
279//===----------------------------------------------------------------------===//
280
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000281bool DeclContext::classof(const Decl *D) {
282 switch (D->getKind()) {
283#define DECL_CONTEXT(Name) case Decl::Name:
284#define DECL_CONTEXT_BASE(Name)
285#include "clang/AST/DeclNodes.def"
286 return true;
287 default:
288#define DECL_CONTEXT_BASE(Name) \
289 if (D->getKind() >= Decl::Name##First && \
290 D->getKind() <= Decl::Name##Last) \
291 return true;
292#include "clang/AST/DeclNodes.def"
293 return false;
294 }
295}
296
Chris Lattner67762a32009-02-20 01:44:05 +0000297/// StoredDeclsList - This is an array of decls optimized a common case of only
298/// containing one entry.
299struct StoredDeclsList {
300 /// Data - If the integer is 0, then the pointer is a NamedDecl*. If the
301 /// integer is 1, then it is a VectorTy;
302 llvm::PointerIntPair<void*, 1, bool> Data;
303
304 /// VectorTy - When in vector form, this is what the Data pointer points to.
305 typedef llvm::SmallVector<NamedDecl*, 4> VectorTy;
306public:
307 StoredDeclsList() {}
308 StoredDeclsList(const StoredDeclsList &RHS) : Data(RHS.Data) {
309 if (isVector())
310 Data.setPointer(new VectorTy(getVector()));
311 }
312
313 ~StoredDeclsList() {
314 // If this is a vector-form, free the vector.
315 if (isVector())
316 delete &getVector();
317 }
318
Chris Lattner01011d42009-02-23 18:17:44 +0000319 StoredDeclsList &operator=(const StoredDeclsList &RHS) {
320 if (isVector())
321 delete &getVector();
322 Data = RHS.Data;
323 if (isVector())
324 Data.setPointer(new VectorTy(getVector()));
325 return *this;
326 }
327
Chris Lattner67762a32009-02-20 01:44:05 +0000328 bool isVector() const { return Data.getInt() != 0; }
329 bool isInline() const { return Data.getInt() == 0; }
330 bool isNull() const { return Data.getPointer() == 0; }
331
332 void setOnlyValue(NamedDecl *ND) {
333 assert(isInline() && "Not inline");
334 Data.setPointer(ND);
335 }
336
337 /// getLookupResult - Return an array of all the decls that this list
338 /// represents.
339 DeclContext::lookup_result getLookupResult() {
340 // If we have a single inline unit, return it.
341 if (isInline()) {
342 assert(!isNull() && "Empty list isn't allowed");
343
344 // Data is a raw pointer to a NamedDecl*, return it.
345 void *Ptr = &Data;
346 return DeclContext::lookup_result((NamedDecl**)Ptr, (NamedDecl**)Ptr+1);
347 }
348
349 // Otherwise, we have a range result.
350 VectorTy &V = getVector();
351 return DeclContext::lookup_result(&V[0], &V[0]+V.size());
352 }
353
354 /// HandleRedeclaration - If this is a redeclaration of an existing decl,
355 /// replace the old one with D and return true. Otherwise return false.
356 bool HandleRedeclaration(NamedDecl *D) {
357 // Most decls only have one entry in their list, special case it.
358 if (isInline()) {
359 if (!D->declarationReplaces(getInlineValue()))
360 return false;
361 setOnlyValue(D);
362 return true;
363 }
364
365 // Determine if this declaration is actually a redeclaration.
366 VectorTy &Vec = getVector();
367 VectorTy::iterator RDI
368 = std::find_if(Vec.begin(), Vec.end(),
369 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
370 D));
371 if (RDI == Vec.end())
372 return false;
373 *RDI = D;
374 return true;
375 }
376
377 /// AddSubsequentDecl - This is called on the second and later decl when it is
378 /// not a redeclaration to merge it into the appropriate place in our list.
379 ///
380 void AddSubsequentDecl(NamedDecl *D) {
381 // If this is the second decl added to the list, convert this to vector
382 // form.
383 if (isInline()) {
384 NamedDecl *OldD = getInlineValue();
385 Data.setInt(1);
386 VectorTy *VT = new VectorTy();
387 VT->push_back(OldD);
388 Data.setPointer(VT);
389 }
390
391 VectorTy &Vec = getVector();
392 if (isa<UsingDirectiveDecl>(D) ||
393 D->getIdentifierNamespace() == Decl::IDNS_Tag)
394 Vec.push_back(D);
395 else if (Vec.back()->getIdentifierNamespace() == Decl::IDNS_Tag) {
396 NamedDecl *TagD = Vec.back();
397 Vec.back() = D;
398 Vec.push_back(TagD);
399 } else
400 Vec.push_back(D);
401 }
402
403
404private:
405 VectorTy &getVector() const {
406 assert(isVector() && "Not in vector form");
407 return *static_cast<VectorTy*>(Data.getPointer());
408 }
409
410 NamedDecl *getInlineValue() const {
411 assert(isInline() && "Not in inline form");
412 return (NamedDecl*)Data.getPointer();
413 }
414};
415
416
417
418typedef llvm::DenseMap<DeclarationName, StoredDeclsList> StoredDeclsMap;
Douglas Gregor44b43212008-12-11 16:49:14 +0000419
420DeclContext::~DeclContext() {
421 unsigned Size = LookupPtr.getInt();
Chris Lattner91942502009-02-20 00:55:03 +0000422 if (Size == LookupIsMap)
423 delete static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
424 else
425 delete [] static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregor44b43212008-12-11 16:49:14 +0000426}
427
428void DeclContext::DestroyDecls(ASTContext &C) {
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000429 for (decl_iterator D = decls_begin(); D != decls_end(); )
430 (*D++)->Destroy(C);
Douglas Gregor44b43212008-12-11 16:49:14 +0000431}
432
Douglas Gregor074149e2009-01-05 19:45:36 +0000433bool DeclContext::isTransparentContext() const {
434 if (DeclKind == Decl::Enum)
435 return true; // FIXME: Check for C++0x scoped enums
436 else if (DeclKind == Decl::LinkageSpec)
437 return true;
Douglas Gregor65100792009-02-26 00:02:51 +0000438 else if (DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000439 return cast<RecordDecl>(this)->isAnonymousStructOrUnion();
Douglas Gregor074149e2009-01-05 19:45:36 +0000440 else if (DeclKind == Decl::Namespace)
441 return false; // FIXME: Check for C++0x inline namespaces
442
443 return false;
444}
445
Steve Naroff0701bbb2009-01-08 17:28:14 +0000446DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor44b43212008-12-11 16:49:14 +0000447 switch (DeclKind) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000448 case Decl::TranslationUnit:
Douglas Gregor074149e2009-01-05 19:45:36 +0000449 case Decl::LinkageSpec:
450 case Decl::Block:
Douglas Gregor44b43212008-12-11 16:49:14 +0000451 // There is only one DeclContext for these entities.
452 return this;
453
454 case Decl::Namespace:
455 // The original namespace is our primary context.
456 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
457
Douglas Gregor44b43212008-12-11 16:49:14 +0000458 case Decl::ObjCMethod:
459 return this;
460
461 case Decl::ObjCInterface:
Steve Naroff0701bbb2009-01-08 17:28:14 +0000462 case Decl::ObjCProtocol:
463 case Decl::ObjCCategory:
Douglas Gregor44b43212008-12-11 16:49:14 +0000464 // FIXME: Can Objective-C interfaces be forward-declared?
465 return this;
466
Steve Naroff0701bbb2009-01-08 17:28:14 +0000467 case Decl::ObjCImplementation:
468 case Decl::ObjCCategoryImpl:
469 return this;
470
Douglas Gregor44b43212008-12-11 16:49:14 +0000471 default:
Douglas Gregorcc636682009-02-17 23:15:12 +0000472 if (DeclKind >= Decl::TagFirst && DeclKind <= Decl::TagLast) {
473 // If this is a tag type that has a definition or is currently
474 // being defined, that definition is our primary context.
Douglas Gregorfc705b82009-02-26 22:19:44 +0000475 if (const TagType *TagT = cast<TagDecl>(this)->TypeForDecl->getAsTagType())
Douglas Gregorcc636682009-02-17 23:15:12 +0000476 if (TagT->isBeingDefined() ||
477 (TagT->getDecl() && TagT->getDecl()->isDefinition()))
478 return TagT->getDecl();
479 return this;
480 }
481
Douglas Gregor44b43212008-12-11 16:49:14 +0000482 assert(DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast &&
483 "Unknown DeclContext kind");
484 return this;
485 }
486}
487
488DeclContext *DeclContext::getNextContext() {
489 switch (DeclKind) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000490 case Decl::Namespace:
491 // Return the next namespace
492 return static_cast<NamespaceDecl*>(this)->getNextNamespace();
493
494 default:
Douglas Gregor44b43212008-12-11 16:49:14 +0000495 return 0;
496 }
497}
498
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000499void DeclContext::addDecl(Decl *D) {
Chris Lattner7f0be132009-02-20 00:56:18 +0000500 assert(D->getLexicalDeclContext() == this &&
501 "Decl inserted into wrong lexical context");
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000502 assert(!D->NextDeclInScope && D != LastDecl &&
503 "Decl already inserted into a DeclContext");
504
505 if (FirstDecl) {
506 LastDecl->NextDeclInScope = D;
507 LastDecl = D;
508 } else {
509 FirstDecl = LastDecl = D;
510 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000511
512 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor40f4e692009-01-20 16:54:50 +0000513 ND->getDeclContext()->makeDeclVisibleInContext(ND);
Douglas Gregor44b43212008-12-11 16:49:14 +0000514}
515
Douglas Gregor074149e2009-01-05 19:45:36 +0000516/// buildLookup - Build the lookup data structure with all of the
517/// declarations in DCtx (and any other contexts linked to it or
518/// transparent contexts nested within it).
Steve Naroff0701bbb2009-01-08 17:28:14 +0000519void DeclContext::buildLookup(DeclContext *DCtx) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000520 for (; DCtx; DCtx = DCtx->getNextContext()) {
Douglas Gregor4f3b8f82009-01-06 07:17:58 +0000521 for (decl_iterator D = DCtx->decls_begin(), DEnd = DCtx->decls_end();
522 D != DEnd; ++D) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000523 // Insert this declaration into the lookup structure
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000524 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor40f4e692009-01-20 16:54:50 +0000525 makeDeclVisibleInContextImpl(ND);
Douglas Gregor074149e2009-01-05 19:45:36 +0000526
527 // If this declaration is itself a transparent declaration context,
528 // add its members (recursively).
529 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
530 if (InnerCtx->isTransparentContext())
Steve Naroff0701bbb2009-01-08 17:28:14 +0000531 buildLookup(InnerCtx->getPrimaryContext());
Douglas Gregor074149e2009-01-05 19:45:36 +0000532 }
533 }
534}
535
Douglas Gregor44b43212008-12-11 16:49:14 +0000536DeclContext::lookup_result
Steve Naroff0701bbb2009-01-08 17:28:14 +0000537DeclContext::lookup(DeclarationName Name) {
538 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor44b43212008-12-11 16:49:14 +0000539 if (PrimaryContext != this)
Steve Naroff0701bbb2009-01-08 17:28:14 +0000540 return PrimaryContext->lookup(Name);
Douglas Gregor44b43212008-12-11 16:49:14 +0000541
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000542 /// If there is no lookup data structure, build one now by walking
Douglas Gregor44b43212008-12-11 16:49:14 +0000543 /// all of the linked DeclContexts (in declaration order!) and
544 /// inserting their values.
Douglas Gregor074149e2009-01-05 19:45:36 +0000545 if (LookupPtr.getPointer() == 0)
Steve Naroff0701bbb2009-01-08 17:28:14 +0000546 buildLookup(this);
Douglas Gregor44b43212008-12-11 16:49:14 +0000547
Douglas Gregor44b43212008-12-11 16:49:14 +0000548 if (isLookupMap()) {
549 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
550 StoredDeclsMap::iterator Pos = Map->find(Name);
Chris Lattner91942502009-02-20 00:55:03 +0000551 if (Pos == Map->end())
552 return lookup_result(0, 0);
Chris Lattner67762a32009-02-20 01:44:05 +0000553 return Pos->second.getLookupResult();
Douglas Gregor44b43212008-12-11 16:49:14 +0000554 }
555
556 // We have a small array. Look into it.
557 unsigned Size = LookupPtr.getInt();
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000558 NamedDecl **Array = static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregore267ff32008-12-11 20:41:00 +0000559 for (unsigned Idx = 0; Idx != Size; ++Idx)
Douglas Gregor44b43212008-12-11 16:49:14 +0000560 if (Array[Idx]->getDeclName() == Name) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000561 unsigned Last = Idx + 1;
562 while (Last != Size && Array[Last]->getDeclName() == Name)
563 ++Last;
564 return lookup_result(&Array[Idx], &Array[Last]);
Douglas Gregor44b43212008-12-11 16:49:14 +0000565 }
566
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000567 return lookup_result(0, 0);
Douglas Gregor44b43212008-12-11 16:49:14 +0000568}
569
570DeclContext::lookup_const_result
Steve Naroff0701bbb2009-01-08 17:28:14 +0000571DeclContext::lookup(DeclarationName Name) const {
572 return const_cast<DeclContext*>(this)->lookup(Name);
Douglas Gregor44b43212008-12-11 16:49:14 +0000573}
574
Douglas Gregor17a9b9e2009-01-07 02:48:43 +0000575const DeclContext *DeclContext::getLookupContext() const {
576 const DeclContext *Ctx = this;
Douglas Gregor72de6672009-01-08 20:45:30 +0000577 // Skip through transparent contexts.
Douglas Gregorce356072009-01-06 23:51:29 +0000578 while (Ctx->isTransparentContext())
579 Ctx = Ctx->getParent();
580 return Ctx;
581}
582
Douglas Gregor88b70942009-02-25 22:02:03 +0000583DeclContext *DeclContext::getEnclosingNamespaceContext() {
584 DeclContext *Ctx = this;
585 // Skip through non-namespace, non-translation-unit contexts.
586 while (!Ctx->isFileContext() || Ctx->isTransparentContext())
587 Ctx = Ctx->getParent();
588 return Ctx->getPrimaryContext();
589}
590
Douglas Gregor40f4e692009-01-20 16:54:50 +0000591void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
Douglas Gregorcc636682009-02-17 23:15:12 +0000592 // FIXME: This feels like a hack. Should DeclarationName support
593 // template-ids, or is there a better way to keep specializations
594 // from being visible?
595 if (isa<ClassTemplateSpecializationDecl>(D))
596 return;
597
Steve Naroff0701bbb2009-01-08 17:28:14 +0000598 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor44b43212008-12-11 16:49:14 +0000599 if (PrimaryContext != this) {
Douglas Gregor40f4e692009-01-20 16:54:50 +0000600 PrimaryContext->makeDeclVisibleInContext(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000601 return;
602 }
603
604 // If we already have a lookup data structure, perform the insertion
605 // into it. Otherwise, be lazy and don't build that structure until
606 // someone asks for it.
607 if (LookupPtr.getPointer())
Douglas Gregor40f4e692009-01-20 16:54:50 +0000608 makeDeclVisibleInContextImpl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +0000609
Douglas Gregor074149e2009-01-05 19:45:36 +0000610 // If we are a transparent context, insert into our parent context,
611 // too. This operation is recursive.
612 if (isTransparentContext())
Douglas Gregor40f4e692009-01-20 16:54:50 +0000613 getParent()->makeDeclVisibleInContext(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000614}
615
Douglas Gregor40f4e692009-01-20 16:54:50 +0000616void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000617 // Skip unnamed declarations.
618 if (!D->getDeclName())
619 return;
620
Douglas Gregorcc636682009-02-17 23:15:12 +0000621 // FIXME: This feels like a hack. Should DeclarationName support
622 // template-ids, or is there a better way to keep specializations
623 // from being visible?
624 if (isa<ClassTemplateSpecializationDecl>(D))
625 return;
626
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000627 bool MayBeRedeclaration = true;
628
Douglas Gregor44b43212008-12-11 16:49:14 +0000629 if (!isLookupMap()) {
630 unsigned Size = LookupPtr.getInt();
631
632 // The lookup data is stored as an array. Search through the array
633 // to find the insertion location.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000634 NamedDecl **Array;
Douglas Gregor44b43212008-12-11 16:49:14 +0000635 if (Size == 0) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000636 Array = new NamedDecl*[LookupIsMap - 1];
Douglas Gregor44b43212008-12-11 16:49:14 +0000637 LookupPtr.setPointer(Array);
638 } else {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000639 Array = static_cast<NamedDecl **>(LookupPtr.getPointer());
Douglas Gregor44b43212008-12-11 16:49:14 +0000640 }
641
642 // We always keep declarations of the same name next to each other
643 // in the array, so that it is easy to return multiple results
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000644 // from lookup().
645 unsigned FirstMatch;
646 for (FirstMatch = 0; FirstMatch != Size; ++FirstMatch)
647 if (Array[FirstMatch]->getDeclName() == D->getDeclName())
Douglas Gregore267ff32008-12-11 20:41:00 +0000648 break;
Douglas Gregor44b43212008-12-11 16:49:14 +0000649
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000650 unsigned InsertPos = FirstMatch;
651 if (FirstMatch != Size) {
652 // We found another declaration with the same name. First
653 // determine whether this is a redeclaration of an existing
654 // declaration in this scope, in which case we will replace the
655 // existing declaration.
656 unsigned LastMatch = FirstMatch;
657 for (; LastMatch != Size; ++LastMatch) {
658 if (Array[LastMatch]->getDeclName() != D->getDeclName())
659 break;
660
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000661 if (D->declarationReplaces(Array[LastMatch])) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000662 // D is a redeclaration of an existing element in the
663 // array. Replace that element with D.
664 Array[LastMatch] = D;
665 return;
666 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000667 }
668
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000669 // [FirstMatch, LastMatch) contains the set of declarations that
670 // have the same name as this declaration. Determine where the
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000671 // declaration D will be inserted into this range.
672 if (D->getKind() == Decl::UsingDirective ||
673 D->getIdentifierNamespace() == Decl::IDNS_Tag)
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000674 InsertPos = LastMatch;
675 else if (Array[LastMatch-1]->getIdentifierNamespace() == Decl::IDNS_Tag)
676 InsertPos = LastMatch - 1;
677 else
678 InsertPos = LastMatch;
Douglas Gregor44b43212008-12-11 16:49:14 +0000679 }
680
681 if (Size < LookupIsMap - 1) {
682 // The new declaration will fit in the array. Insert the new
683 // declaration at the position Match in the array.
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000684 for (unsigned Idx = Size; Idx > InsertPos; --Idx)
Douglas Gregor44b43212008-12-11 16:49:14 +0000685 Array[Idx] = Array[Idx-1];
686
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000687 Array[InsertPos] = D;
Douglas Gregor44b43212008-12-11 16:49:14 +0000688 LookupPtr.setInt(Size + 1);
689 return;
690 }
691
692 // We've reached capacity in this array. Create a map and copy in
693 // all of the declarations that were stored in the array.
694 StoredDeclsMap *Map = new StoredDeclsMap(16);
695 LookupPtr.setPointer(Map);
696 LookupPtr.setInt(LookupIsMap);
Douglas Gregore267ff32008-12-11 20:41:00 +0000697 for (unsigned Idx = 0; Idx != LookupIsMap - 1; ++Idx)
Douglas Gregor40f4e692009-01-20 16:54:50 +0000698 makeDeclVisibleInContextImpl(Array[Idx]);
Douglas Gregor44b43212008-12-11 16:49:14 +0000699 delete [] Array;
700
701 // Fall through to perform insertion into the map.
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000702 MayBeRedeclaration = false;
703 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000704
705 // Insert this declaration into the map.
Chris Lattner67762a32009-02-20 01:44:05 +0000706 StoredDeclsMap &Map = *static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
707 StoredDeclsList &DeclNameEntries = Map[D->getDeclName()];
708 if (DeclNameEntries.isNull()) {
709 DeclNameEntries.setOnlyValue(D);
Chris Lattnerbd6c8002009-02-19 07:00:44 +0000710 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000711 }
Chris Lattner91942502009-02-20 00:55:03 +0000712
Chris Lattnerbdc3d002009-02-20 01:10:07 +0000713 // If it is possible that this is a redeclaration, check to see if there is
714 // already a decl for which declarationReplaces returns true. If there is
715 // one, just replace it and return.
Chris Lattner67762a32009-02-20 01:44:05 +0000716 if (MayBeRedeclaration && DeclNameEntries.HandleRedeclaration(D))
717 return;
Chris Lattner91942502009-02-20 00:55:03 +0000718
Chris Lattnerbd6c8002009-02-19 07:00:44 +0000719 // Put this declaration into the appropriate slot.
Chris Lattner67762a32009-02-20 01:44:05 +0000720 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000721}
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000722
723/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
724/// this context.
725DeclContext::udir_iterator_range DeclContext::getUsingDirectives() const {
726 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
727 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
728 reinterpret_cast<udir_iterator>(Result.second));
729}
730