blob: d45ad4177c71a00c89f2aa9f856c22ec17d39bc1 [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
Chris Lattner769dbdf2009-03-27 20:18:19 +0000120// Out-of-line virtual method providing a home for Decl.
121Decl::~Decl() {
122 if (isOutOfSemaDC())
123 delete getMultipleDC();
124
125 assert(!HasAttrs && "attributes should have been freed by Destroy");
126}
127
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000128void Decl::setDeclContext(DeclContext *DC) {
129 if (isOutOfSemaDC())
130 delete getMultipleDC();
131
Chris Lattneree219fd2009-03-29 06:06:59 +0000132 DeclCtx = DC;
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000133}
134
135void Decl::setLexicalDeclContext(DeclContext *DC) {
136 if (DC == getLexicalDeclContext())
137 return;
138
139 if (isInSemaDC()) {
140 MultipleDC *MDC = new MultipleDC();
141 MDC->SemanticDC = getDeclContext();
142 MDC->LexicalDC = DC;
Chris Lattneree219fd2009-03-29 06:06:59 +0000143 DeclCtx = MDC;
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000144 } else {
145 getMultipleDC()->LexicalDC = DC;
146 }
147}
148
Chris Lattner769dbdf2009-03-27 20:18:19 +0000149unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
150 switch (DeclKind) {
151 default:
152 if (DeclKind >= FunctionFirst && DeclKind <= FunctionLast)
153 return IDNS_Ordinary;
154 assert(0 && "Unknown decl kind!");
155 case OverloadedFunction:
156 case Typedef:
157 case EnumConstant:
158 case Var:
159 case ImplicitParam:
160 case ParmVar:
161 case OriginalParmVar:
162 case NonTypeTemplateParm:
163 case ObjCMethod:
164 case ObjCContainer:
165 case ObjCCategory:
166 case ObjCInterface:
167 case ObjCCategoryImpl:
168 case ObjCProperty:
169 case ObjCCompatibleAlias:
170 return IDNS_Ordinary;
171
172 case ObjCProtocol:
173 return IDNS_Protocol;
174
175 case Field:
176 case ObjCAtDefsField:
177 case ObjCIvar:
178 return IDNS_Member;
179
180 case Record:
181 case CXXRecord:
182 case Enum:
183 case TemplateTypeParm:
184 return IDNS_Tag;
185
186 case Namespace:
187 case Template:
188 case FunctionTemplate:
189 case ClassTemplate:
190 case TemplateTemplateParm:
Anders Carlssonfaf0e872009-03-28 23:02:53 +0000191 case NamespaceAlias:
Chris Lattner769dbdf2009-03-27 20:18:19 +0000192 return IDNS_Tag | IDNS_Ordinary;
193
194 // Never have names.
195 case LinkageSpec:
196 case FileScopeAsm:
197 case StaticAssert:
198 case ObjCClass:
199 case ObjCImplementation:
200 case ObjCPropertyImpl:
201 case ObjCForwardProtocol:
202 case Block:
203 case TranslationUnit:
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000204
Chris Lattner769dbdf2009-03-27 20:18:19 +0000205 // Aren't looked up?
206 case UsingDirective:
207 case ClassTemplateSpecialization:
208 return 0;
209 }
Eli Friedman56d29372008-06-07 16:52:53 +0000210}
211
212void Decl::addAttr(Attr *NewAttr) {
213 if (!DeclAttrs)
214 DeclAttrs = new DeclAttrMapTy();
215
216 Attr *&ExistingAttr = (*DeclAttrs)[this];
217
218 NewAttr->setNext(ExistingAttr);
219 ExistingAttr = NewAttr;
220
221 HasAttrs = true;
222}
223
224void Decl::invalidateAttrs() {
225 if (!HasAttrs) return;
226
227 HasAttrs = false;
228 (*DeclAttrs)[this] = 0;
229 DeclAttrs->erase(this);
230
231 if (DeclAttrs->empty()) {
232 delete DeclAttrs;
233 DeclAttrs = 0;
234 }
235}
236
Chris Lattner81abbdd2009-03-21 06:27:31 +0000237const Attr *Decl::getAttrsImpl() const {
238 assert(HasAttrs && "getAttrs() should verify this!");
Eli Friedman56d29372008-06-07 16:52:53 +0000239 return (*DeclAttrs)[this];
240}
241
242void Decl::swapAttrs(Decl *RHS) {
243 bool HasLHSAttr = this->HasAttrs;
244 bool HasRHSAttr = RHS->HasAttrs;
245
246 // Usually, neither decl has attrs, nothing to do.
247 if (!HasLHSAttr && !HasRHSAttr) return;
248
249 // If 'this' has no attrs, swap the other way.
250 if (!HasLHSAttr)
251 return RHS->swapAttrs(this);
252
253 // Handle the case when both decls have attrs.
254 if (HasRHSAttr) {
255 std::swap((*DeclAttrs)[this], (*DeclAttrs)[RHS]);
256 return;
257 }
258
259 // Otherwise, LHS has an attr and RHS doesn't.
260 (*DeclAttrs)[RHS] = (*DeclAttrs)[this];
261 (*DeclAttrs).erase(this);
262 this->HasAttrs = false;
263 RHS->HasAttrs = true;
264}
265
266
Chris Lattnercc581472009-03-04 06:05:19 +0000267void Decl::Destroy(ASTContext &C) {
268 // Free attributes for this decl.
269 if (HasAttrs) {
270 DeclAttrMapTy::iterator it = DeclAttrs->find(this);
271 assert(it != DeclAttrs->end() && "No attrs found but HasAttrs is true!");
272
273 // release attributes.
274 it->second->Destroy(C);
275 invalidateAttrs();
276 HasAttrs = false;
277 }
278
Douglas Gregora0fc55f2009-01-13 19:47:12 +0000279#if 0
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000280 // FIXME: Once ownership is fully understood, we can enable this code
281 if (DeclContext *DC = dyn_cast<DeclContext>(this))
282 DC->decls_begin()->Destroy(C);
Eli Friedman56d29372008-06-07 16:52:53 +0000283
Chris Lattner244a67d2009-03-28 06:04:26 +0000284 // Observe the unrolled recursion. By setting N->NextDeclInContext = 0x0
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000285 // within the loop, only the Destroy method for the first Decl
286 // will deallocate all of the Decls in a chain.
287
Chris Lattner244a67d2009-03-28 06:04:26 +0000288 Decl* N = getNextDeclInContext();
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000289
290 while (N) {
Chris Lattner244a67d2009-03-28 06:04:26 +0000291 Decl* Tmp = N->getNextDeclInContext();
292 N->NextDeclInContext = 0;
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000293 N->Destroy(C);
294 N = Tmp;
Eli Friedman56d29372008-06-07 16:52:53 +0000295 }
Douglas Gregora0fc55f2009-01-13 19:47:12 +0000296
Eli Friedman56d29372008-06-07 16:52:53 +0000297 this->~Decl();
Steve Naroff3e970492009-01-27 21:25:57 +0000298 C.Deallocate((void *)this);
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000299#endif
Eli Friedman56d29372008-06-07 16:52:53 +0000300}
301
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000302Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000303 Decl::Kind DK = D->getDeclKind();
304 switch(DK) {
305#define DECL_CONTEXT(Name) \
306 case Decl::Name: \
307 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
308#define DECL_CONTEXT_BASE(Name)
309#include "clang/AST/DeclNodes.def"
310 default:
311#define DECL_CONTEXT_BASE(Name) \
312 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
313 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
314#include "clang/AST/DeclNodes.def"
315 assert(false && "a decl that inherits DeclContext isn't handled");
316 return 0;
317 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000318}
319
320DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000321 Decl::Kind DK = D->getKind();
322 switch(DK) {
323#define DECL_CONTEXT(Name) \
324 case Decl::Name: \
325 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
326#define DECL_CONTEXT_BASE(Name)
327#include "clang/AST/DeclNodes.def"
328 default:
329#define DECL_CONTEXT_BASE(Name) \
330 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
331 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
332#include "clang/AST/DeclNodes.def"
333 assert(false && "a decl that inherits DeclContext isn't handled");
334 return 0;
335 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000336}
337
Anders Carlsson1329c272009-03-25 23:38:06 +0000338#ifndef NDEBUG
339void Decl::CheckAccessDeclContext() const {
340 assert((Access != AS_none || !isa<CXXRecordDecl>(getDeclContext())) &&
341 "Access specifier is AS_none inside a record decl");
342}
343
344#endif
345
Eli Friedman56d29372008-06-07 16:52:53 +0000346//===----------------------------------------------------------------------===//
347// DeclContext Implementation
348//===----------------------------------------------------------------------===//
349
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000350bool DeclContext::classof(const Decl *D) {
351 switch (D->getKind()) {
352#define DECL_CONTEXT(Name) case Decl::Name:
353#define DECL_CONTEXT_BASE(Name)
354#include "clang/AST/DeclNodes.def"
355 return true;
356 default:
357#define DECL_CONTEXT_BASE(Name) \
358 if (D->getKind() >= Decl::Name##First && \
359 D->getKind() <= Decl::Name##Last) \
360 return true;
361#include "clang/AST/DeclNodes.def"
362 return false;
363 }
364}
365
Chris Lattner67762a32009-02-20 01:44:05 +0000366/// StoredDeclsList - This is an array of decls optimized a common case of only
367/// containing one entry.
368struct StoredDeclsList {
369 /// Data - If the integer is 0, then the pointer is a NamedDecl*. If the
370 /// integer is 1, then it is a VectorTy;
371 llvm::PointerIntPair<void*, 1, bool> Data;
372
373 /// VectorTy - When in vector form, this is what the Data pointer points to.
374 typedef llvm::SmallVector<NamedDecl*, 4> VectorTy;
375public:
376 StoredDeclsList() {}
377 StoredDeclsList(const StoredDeclsList &RHS) : Data(RHS.Data) {
378 if (isVector())
379 Data.setPointer(new VectorTy(getVector()));
380 }
381
382 ~StoredDeclsList() {
383 // If this is a vector-form, free the vector.
384 if (isVector())
385 delete &getVector();
386 }
387
Chris Lattner01011d42009-02-23 18:17:44 +0000388 StoredDeclsList &operator=(const StoredDeclsList &RHS) {
389 if (isVector())
390 delete &getVector();
391 Data = RHS.Data;
392 if (isVector())
393 Data.setPointer(new VectorTy(getVector()));
394 return *this;
395 }
396
Chris Lattner67762a32009-02-20 01:44:05 +0000397 bool isVector() const { return Data.getInt() != 0; }
398 bool isInline() const { return Data.getInt() == 0; }
399 bool isNull() const { return Data.getPointer() == 0; }
400
401 void setOnlyValue(NamedDecl *ND) {
402 assert(isInline() && "Not inline");
403 Data.setPointer(ND);
404 }
405
406 /// getLookupResult - Return an array of all the decls that this list
407 /// represents.
408 DeclContext::lookup_result getLookupResult() {
409 // If we have a single inline unit, return it.
410 if (isInline()) {
411 assert(!isNull() && "Empty list isn't allowed");
412
413 // Data is a raw pointer to a NamedDecl*, return it.
414 void *Ptr = &Data;
415 return DeclContext::lookup_result((NamedDecl**)Ptr, (NamedDecl**)Ptr+1);
416 }
417
418 // Otherwise, we have a range result.
419 VectorTy &V = getVector();
420 return DeclContext::lookup_result(&V[0], &V[0]+V.size());
421 }
422
423 /// HandleRedeclaration - If this is a redeclaration of an existing decl,
424 /// replace the old one with D and return true. Otherwise return false.
425 bool HandleRedeclaration(NamedDecl *D) {
426 // Most decls only have one entry in their list, special case it.
427 if (isInline()) {
428 if (!D->declarationReplaces(getInlineValue()))
429 return false;
430 setOnlyValue(D);
431 return true;
432 }
433
434 // Determine if this declaration is actually a redeclaration.
435 VectorTy &Vec = getVector();
436 VectorTy::iterator RDI
437 = std::find_if(Vec.begin(), Vec.end(),
438 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
439 D));
440 if (RDI == Vec.end())
441 return false;
442 *RDI = D;
443 return true;
444 }
445
446 /// AddSubsequentDecl - This is called on the second and later decl when it is
447 /// not a redeclaration to merge it into the appropriate place in our list.
448 ///
449 void AddSubsequentDecl(NamedDecl *D) {
450 // If this is the second decl added to the list, convert this to vector
451 // form.
452 if (isInline()) {
453 NamedDecl *OldD = getInlineValue();
454 Data.setInt(1);
455 VectorTy *VT = new VectorTy();
456 VT->push_back(OldD);
457 Data.setPointer(VT);
458 }
459
460 VectorTy &Vec = getVector();
461 if (isa<UsingDirectiveDecl>(D) ||
462 D->getIdentifierNamespace() == Decl::IDNS_Tag)
463 Vec.push_back(D);
464 else if (Vec.back()->getIdentifierNamespace() == Decl::IDNS_Tag) {
465 NamedDecl *TagD = Vec.back();
466 Vec.back() = D;
467 Vec.push_back(TagD);
468 } else
469 Vec.push_back(D);
470 }
471
472
473private:
474 VectorTy &getVector() const {
475 assert(isVector() && "Not in vector form");
476 return *static_cast<VectorTy*>(Data.getPointer());
477 }
478
479 NamedDecl *getInlineValue() const {
480 assert(isInline() && "Not in inline form");
481 return (NamedDecl*)Data.getPointer();
482 }
483};
484
485
486
487typedef llvm::DenseMap<DeclarationName, StoredDeclsList> StoredDeclsMap;
Douglas Gregor44b43212008-12-11 16:49:14 +0000488
489DeclContext::~DeclContext() {
Chris Lattner769dbdf2009-03-27 20:18:19 +0000490 if (isLookupMap())
Chris Lattner91942502009-02-20 00:55:03 +0000491 delete static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
492 else
493 delete [] static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregor44b43212008-12-11 16:49:14 +0000494}
495
496void DeclContext::DestroyDecls(ASTContext &C) {
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000497 for (decl_iterator D = decls_begin(); D != decls_end(); )
498 (*D++)->Destroy(C);
Douglas Gregor44b43212008-12-11 16:49:14 +0000499}
500
Douglas Gregor074149e2009-01-05 19:45:36 +0000501bool DeclContext::isTransparentContext() const {
502 if (DeclKind == Decl::Enum)
503 return true; // FIXME: Check for C++0x scoped enums
504 else if (DeclKind == Decl::LinkageSpec)
505 return true;
Douglas Gregor65100792009-02-26 00:02:51 +0000506 else if (DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000507 return cast<RecordDecl>(this)->isAnonymousStructOrUnion();
Douglas Gregor074149e2009-01-05 19:45:36 +0000508 else if (DeclKind == Decl::Namespace)
509 return false; // FIXME: Check for C++0x inline namespaces
510
511 return false;
512}
513
Steve Naroff0701bbb2009-01-08 17:28:14 +0000514DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor44b43212008-12-11 16:49:14 +0000515 switch (DeclKind) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000516 case Decl::TranslationUnit:
Douglas Gregor074149e2009-01-05 19:45:36 +0000517 case Decl::LinkageSpec:
518 case Decl::Block:
Douglas Gregor44b43212008-12-11 16:49:14 +0000519 // There is only one DeclContext for these entities.
520 return this;
521
522 case Decl::Namespace:
523 // The original namespace is our primary context.
524 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
525
Douglas Gregor44b43212008-12-11 16:49:14 +0000526 case Decl::ObjCMethod:
527 return this;
528
529 case Decl::ObjCInterface:
Steve Naroff0701bbb2009-01-08 17:28:14 +0000530 case Decl::ObjCProtocol:
531 case Decl::ObjCCategory:
Douglas Gregor44b43212008-12-11 16:49:14 +0000532 // FIXME: Can Objective-C interfaces be forward-declared?
533 return this;
534
Steve Naroff0701bbb2009-01-08 17:28:14 +0000535 case Decl::ObjCImplementation:
536 case Decl::ObjCCategoryImpl:
537 return this;
538
Douglas Gregor44b43212008-12-11 16:49:14 +0000539 default:
Douglas Gregorcc636682009-02-17 23:15:12 +0000540 if (DeclKind >= Decl::TagFirst && DeclKind <= Decl::TagLast) {
541 // If this is a tag type that has a definition or is currently
542 // being defined, that definition is our primary context.
Chris Lattner244a67d2009-03-28 06:04:26 +0000543 if (const TagType *TagT =cast<TagDecl>(this)->TypeForDecl->getAsTagType())
Douglas Gregorcc636682009-02-17 23:15:12 +0000544 if (TagT->isBeingDefined() ||
545 (TagT->getDecl() && TagT->getDecl()->isDefinition()))
546 return TagT->getDecl();
547 return this;
548 }
549
Douglas Gregor44b43212008-12-11 16:49:14 +0000550 assert(DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast &&
551 "Unknown DeclContext kind");
552 return this;
553 }
554}
555
556DeclContext *DeclContext::getNextContext() {
557 switch (DeclKind) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000558 case Decl::Namespace:
559 // Return the next namespace
560 return static_cast<NamespaceDecl*>(this)->getNextNamespace();
561
562 default:
Douglas Gregor44b43212008-12-11 16:49:14 +0000563 return 0;
564 }
565}
566
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000567void DeclContext::addDecl(Decl *D) {
Chris Lattner7f0be132009-02-20 00:56:18 +0000568 assert(D->getLexicalDeclContext() == this &&
569 "Decl inserted into wrong lexical context");
Chris Lattner244a67d2009-03-28 06:04:26 +0000570 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000571 "Decl already inserted into a DeclContext");
572
573 if (FirstDecl) {
Chris Lattner244a67d2009-03-28 06:04:26 +0000574 LastDecl->NextDeclInContext = D;
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000575 LastDecl = D;
576 } else {
577 FirstDecl = LastDecl = D;
578 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000579
580 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor40f4e692009-01-20 16:54:50 +0000581 ND->getDeclContext()->makeDeclVisibleInContext(ND);
Douglas Gregor44b43212008-12-11 16:49:14 +0000582}
583
Douglas Gregor074149e2009-01-05 19:45:36 +0000584/// buildLookup - Build the lookup data structure with all of the
585/// declarations in DCtx (and any other contexts linked to it or
586/// transparent contexts nested within it).
Steve Naroff0701bbb2009-01-08 17:28:14 +0000587void DeclContext::buildLookup(DeclContext *DCtx) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000588 for (; DCtx; DCtx = DCtx->getNextContext()) {
Douglas Gregor4f3b8f82009-01-06 07:17:58 +0000589 for (decl_iterator D = DCtx->decls_begin(), DEnd = DCtx->decls_end();
590 D != DEnd; ++D) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000591 // Insert this declaration into the lookup structure
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000592 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor40f4e692009-01-20 16:54:50 +0000593 makeDeclVisibleInContextImpl(ND);
Douglas Gregor074149e2009-01-05 19:45:36 +0000594
595 // If this declaration is itself a transparent declaration context,
596 // add its members (recursively).
597 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
598 if (InnerCtx->isTransparentContext())
Steve Naroff0701bbb2009-01-08 17:28:14 +0000599 buildLookup(InnerCtx->getPrimaryContext());
Douglas Gregor074149e2009-01-05 19:45:36 +0000600 }
601 }
602}
603
Douglas Gregor44b43212008-12-11 16:49:14 +0000604DeclContext::lookup_result
Steve Naroff0701bbb2009-01-08 17:28:14 +0000605DeclContext::lookup(DeclarationName Name) {
606 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor44b43212008-12-11 16:49:14 +0000607 if (PrimaryContext != this)
Steve Naroff0701bbb2009-01-08 17:28:14 +0000608 return PrimaryContext->lookup(Name);
Douglas Gregor44b43212008-12-11 16:49:14 +0000609
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000610 /// If there is no lookup data structure, build one now by walking
Douglas Gregor44b43212008-12-11 16:49:14 +0000611 /// all of the linked DeclContexts (in declaration order!) and
612 /// inserting their values.
Douglas Gregor074149e2009-01-05 19:45:36 +0000613 if (LookupPtr.getPointer() == 0)
Steve Naroff0701bbb2009-01-08 17:28:14 +0000614 buildLookup(this);
Douglas Gregor44b43212008-12-11 16:49:14 +0000615
Douglas Gregor44b43212008-12-11 16:49:14 +0000616 if (isLookupMap()) {
617 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
618 StoredDeclsMap::iterator Pos = Map->find(Name);
Chris Lattner91942502009-02-20 00:55:03 +0000619 if (Pos == Map->end())
620 return lookup_result(0, 0);
Chris Lattner67762a32009-02-20 01:44:05 +0000621 return Pos->second.getLookupResult();
Douglas Gregor44b43212008-12-11 16:49:14 +0000622 }
623
624 // We have a small array. Look into it.
625 unsigned Size = LookupPtr.getInt();
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000626 NamedDecl **Array = static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregore267ff32008-12-11 20:41:00 +0000627 for (unsigned Idx = 0; Idx != Size; ++Idx)
Douglas Gregor44b43212008-12-11 16:49:14 +0000628 if (Array[Idx]->getDeclName() == Name) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000629 unsigned Last = Idx + 1;
630 while (Last != Size && Array[Last]->getDeclName() == Name)
631 ++Last;
632 return lookup_result(&Array[Idx], &Array[Last]);
Douglas Gregor44b43212008-12-11 16:49:14 +0000633 }
634
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000635 return lookup_result(0, 0);
Douglas Gregor44b43212008-12-11 16:49:14 +0000636}
637
638DeclContext::lookup_const_result
Steve Naroff0701bbb2009-01-08 17:28:14 +0000639DeclContext::lookup(DeclarationName Name) const {
640 return const_cast<DeclContext*>(this)->lookup(Name);
Douglas Gregor44b43212008-12-11 16:49:14 +0000641}
642
Chris Lattner0cf2b192009-03-27 19:19:59 +0000643DeclContext *DeclContext::getLookupContext() {
644 DeclContext *Ctx = this;
Douglas Gregor72de6672009-01-08 20:45:30 +0000645 // Skip through transparent contexts.
Douglas Gregorce356072009-01-06 23:51:29 +0000646 while (Ctx->isTransparentContext())
647 Ctx = Ctx->getParent();
648 return Ctx;
649}
650
Douglas Gregor88b70942009-02-25 22:02:03 +0000651DeclContext *DeclContext::getEnclosingNamespaceContext() {
652 DeclContext *Ctx = this;
653 // Skip through non-namespace, non-translation-unit contexts.
654 while (!Ctx->isFileContext() || Ctx->isTransparentContext())
655 Ctx = Ctx->getParent();
656 return Ctx->getPrimaryContext();
657}
658
Douglas Gregor40f4e692009-01-20 16:54:50 +0000659void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
Douglas Gregorcc636682009-02-17 23:15:12 +0000660 // FIXME: This feels like a hack. Should DeclarationName support
661 // template-ids, or is there a better way to keep specializations
662 // from being visible?
663 if (isa<ClassTemplateSpecializationDecl>(D))
664 return;
665
Steve Naroff0701bbb2009-01-08 17:28:14 +0000666 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor44b43212008-12-11 16:49:14 +0000667 if (PrimaryContext != this) {
Douglas Gregor40f4e692009-01-20 16:54:50 +0000668 PrimaryContext->makeDeclVisibleInContext(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000669 return;
670 }
671
672 // If we already have a lookup data structure, perform the insertion
673 // into it. Otherwise, be lazy and don't build that structure until
674 // someone asks for it.
675 if (LookupPtr.getPointer())
Douglas Gregor40f4e692009-01-20 16:54:50 +0000676 makeDeclVisibleInContextImpl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +0000677
Douglas Gregor074149e2009-01-05 19:45:36 +0000678 // If we are a transparent context, insert into our parent context,
679 // too. This operation is recursive.
680 if (isTransparentContext())
Douglas Gregor40f4e692009-01-20 16:54:50 +0000681 getParent()->makeDeclVisibleInContext(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000682}
683
Douglas Gregor40f4e692009-01-20 16:54:50 +0000684void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000685 // Skip unnamed declarations.
686 if (!D->getDeclName())
687 return;
688
Douglas Gregorcc636682009-02-17 23:15:12 +0000689 // FIXME: This feels like a hack. Should DeclarationName support
690 // template-ids, or is there a better way to keep specializations
691 // from being visible?
692 if (isa<ClassTemplateSpecializationDecl>(D))
693 return;
694
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000695 bool MayBeRedeclaration = true;
696
Douglas Gregor44b43212008-12-11 16:49:14 +0000697 if (!isLookupMap()) {
698 unsigned Size = LookupPtr.getInt();
699
700 // The lookup data is stored as an array. Search through the array
701 // to find the insertion location.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000702 NamedDecl **Array;
Douglas Gregor44b43212008-12-11 16:49:14 +0000703 if (Size == 0) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000704 Array = new NamedDecl*[LookupIsMap - 1];
Douglas Gregor44b43212008-12-11 16:49:14 +0000705 LookupPtr.setPointer(Array);
706 } else {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000707 Array = static_cast<NamedDecl **>(LookupPtr.getPointer());
Douglas Gregor44b43212008-12-11 16:49:14 +0000708 }
709
710 // We always keep declarations of the same name next to each other
711 // in the array, so that it is easy to return multiple results
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000712 // from lookup().
713 unsigned FirstMatch;
714 for (FirstMatch = 0; FirstMatch != Size; ++FirstMatch)
715 if (Array[FirstMatch]->getDeclName() == D->getDeclName())
Douglas Gregore267ff32008-12-11 20:41:00 +0000716 break;
Douglas Gregor44b43212008-12-11 16:49:14 +0000717
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000718 unsigned InsertPos = FirstMatch;
719 if (FirstMatch != Size) {
720 // We found another declaration with the same name. First
721 // determine whether this is a redeclaration of an existing
722 // declaration in this scope, in which case we will replace the
723 // existing declaration.
724 unsigned LastMatch = FirstMatch;
725 for (; LastMatch != Size; ++LastMatch) {
726 if (Array[LastMatch]->getDeclName() != D->getDeclName())
727 break;
728
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000729 if (D->declarationReplaces(Array[LastMatch])) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000730 // D is a redeclaration of an existing element in the
731 // array. Replace that element with D.
732 Array[LastMatch] = D;
733 return;
734 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000735 }
736
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000737 // [FirstMatch, LastMatch) contains the set of declarations that
738 // have the same name as this declaration. Determine where the
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000739 // declaration D will be inserted into this range.
740 if (D->getKind() == Decl::UsingDirective ||
741 D->getIdentifierNamespace() == Decl::IDNS_Tag)
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000742 InsertPos = LastMatch;
743 else if (Array[LastMatch-1]->getIdentifierNamespace() == Decl::IDNS_Tag)
744 InsertPos = LastMatch - 1;
745 else
746 InsertPos = LastMatch;
Douglas Gregor44b43212008-12-11 16:49:14 +0000747 }
748
749 if (Size < LookupIsMap - 1) {
750 // The new declaration will fit in the array. Insert the new
751 // declaration at the position Match in the array.
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000752 for (unsigned Idx = Size; Idx > InsertPos; --Idx)
Douglas Gregor44b43212008-12-11 16:49:14 +0000753 Array[Idx] = Array[Idx-1];
754
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000755 Array[InsertPos] = D;
Douglas Gregor44b43212008-12-11 16:49:14 +0000756 LookupPtr.setInt(Size + 1);
757 return;
758 }
759
760 // We've reached capacity in this array. Create a map and copy in
761 // all of the declarations that were stored in the array.
762 StoredDeclsMap *Map = new StoredDeclsMap(16);
763 LookupPtr.setPointer(Map);
764 LookupPtr.setInt(LookupIsMap);
Douglas Gregore267ff32008-12-11 20:41:00 +0000765 for (unsigned Idx = 0; Idx != LookupIsMap - 1; ++Idx)
Douglas Gregor40f4e692009-01-20 16:54:50 +0000766 makeDeclVisibleInContextImpl(Array[Idx]);
Douglas Gregor44b43212008-12-11 16:49:14 +0000767 delete [] Array;
768
769 // Fall through to perform insertion into the map.
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000770 MayBeRedeclaration = false;
771 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000772
773 // Insert this declaration into the map.
Chris Lattner67762a32009-02-20 01:44:05 +0000774 StoredDeclsMap &Map = *static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
775 StoredDeclsList &DeclNameEntries = Map[D->getDeclName()];
776 if (DeclNameEntries.isNull()) {
777 DeclNameEntries.setOnlyValue(D);
Chris Lattnerbd6c8002009-02-19 07:00:44 +0000778 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000779 }
Chris Lattner91942502009-02-20 00:55:03 +0000780
Chris Lattnerbdc3d002009-02-20 01:10:07 +0000781 // If it is possible that this is a redeclaration, check to see if there is
782 // already a decl for which declarationReplaces returns true. If there is
783 // one, just replace it and return.
Chris Lattner67762a32009-02-20 01:44:05 +0000784 if (MayBeRedeclaration && DeclNameEntries.HandleRedeclaration(D))
785 return;
Chris Lattner91942502009-02-20 00:55:03 +0000786
Chris Lattnerbd6c8002009-02-19 07:00:44 +0000787 // Put this declaration into the appropriate slot.
Chris Lattner67762a32009-02-20 01:44:05 +0000788 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000789}
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000790
791/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
792/// this context.
793DeclContext::udir_iterator_range DeclContext::getUsingDirectives() const {
794 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
795 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
796 reinterpret_cast<udir_iterator>(Result.second));
797}
798