blob: 84aa81ca76db6d05d53c63bd06dc19ba23b70af1 [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- 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"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclContextInternals.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/Type.h"
23#include "clang/AST/Stmt.h"
24#include "clang/AST/StmtCXX.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/Support/raw_ostream.h"
27#include <algorithm>
28#include <cstdio>
29#include <vector>
30using namespace clang;
31
32//===----------------------------------------------------------------------===//
33// Statistics
34//===----------------------------------------------------------------------===//
35
36#define DECL(Derived, Base) static int n##Derived##s = 0;
37#include "clang/AST/DeclNodes.def"
38
39static bool StatSwitch = false;
40
41const char *Decl::getDeclKindName() const {
42 switch (DeclKind) {
43 default: assert(0 && "Declaration not in DeclNodes.def!");
44#define DECL(Derived, Base) case Derived: return #Derived;
45#include "clang/AST/DeclNodes.def"
46 }
47}
48
49const char *DeclContext::getDeclKindName() const {
50 switch (DeclKind) {
51 default: assert(0 && "Declaration context not in DeclNodes.def!");
52#define DECL(Derived, Base) case Decl::Derived: return #Derived;
53#include "clang/AST/DeclNodes.def"
54 }
55}
56
57bool Decl::CollectingStats(bool Enable) {
58 if (Enable) StatSwitch = true;
59 return StatSwitch;
60}
61
62void Decl::PrintStats() {
63 fprintf(stderr, "*** Decl Stats:\n");
64
65 int totalDecls = 0;
66#define DECL(Derived, Base) totalDecls += n##Derived##s;
67#include "clang/AST/DeclNodes.def"
68 fprintf(stderr, " %d decls total.\n", totalDecls);
69
70 int totalBytes = 0;
71#define DECL(Derived, Base) \
72 if (n##Derived##s > 0) { \
73 totalBytes += (int)(n##Derived##s * sizeof(Derived##Decl)); \
74 fprintf(stderr, " %d " #Derived " decls, %d each (%d bytes)\n", \
75 n##Derived##s, (int)sizeof(Derived##Decl), \
76 (int)(n##Derived##s * sizeof(Derived##Decl))); \
77 }
78#include "clang/AST/DeclNodes.def"
79
80 fprintf(stderr, "Total bytes = %d\n", totalBytes);
81}
82
83void Decl::addDeclKind(Kind k) {
84 switch (k) {
85 default: assert(0 && "Declaration not in DeclNodes.def!");
86#define DECL(Derived, Base) case Derived: ++n##Derived##s; break;
87#include "clang/AST/DeclNodes.def"
88 }
89}
90
91bool Decl::isTemplateParameterPack() const {
92 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
93 return TTP->isParameterPack();
94
95 return false;
96}
97
98bool Decl::isFunctionOrFunctionTemplate() const {
99 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
100 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
101
102 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
103}
104
105bool Decl::isDefinedOutsideFunctionOrMethod() const {
106 for (const DeclContext *DC = getDeclContext();
107 DC && !DC->isTranslationUnit();
108 DC = DC->getParent())
109 if (DC->isFunctionOrMethod())
110 return false;
111
112 return true;
113}
114
115
116//===----------------------------------------------------------------------===//
117// PrettyStackTraceDecl Implementation
118//===----------------------------------------------------------------------===//
119
120void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const {
121 SourceLocation TheLoc = Loc;
122 if (TheLoc.isInvalid() && TheDecl)
123 TheLoc = TheDecl->getLocation();
124
125 if (TheLoc.isValid()) {
126 TheLoc.print(OS, SM);
127 OS << ": ";
128 }
129
130 OS << Message;
131
132 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
133 OS << " '" << DN->getQualifiedNameAsString() << '\'';
134 OS << '\n';
135}
136
137//===----------------------------------------------------------------------===//
138// Decl Implementation
139//===----------------------------------------------------------------------===//
140
141// Out-of-line virtual method providing a home for Decl.
142Decl::~Decl() {
143 assert(!HasAttrs && "attributes should have been freed by Destroy");
144}
145
146void Decl::setDeclContext(DeclContext *DC) {
147 if (isOutOfSemaDC())
148 delete getMultipleDC();
149
150 DeclCtx = DC;
151}
152
153void Decl::setLexicalDeclContext(DeclContext *DC) {
154 if (DC == getLexicalDeclContext())
155 return;
156
157 if (isInSemaDC()) {
158 MultipleDC *MDC = new (getASTContext()) MultipleDC();
159 MDC->SemanticDC = getDeclContext();
160 MDC->LexicalDC = DC;
161 DeclCtx = MDC;
162 } else {
163 getMultipleDC()->LexicalDC = DC;
164 }
165}
166
167bool Decl::isInAnonymousNamespace() const {
168 const DeclContext *DC = getDeclContext();
169 do {
170 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
171 if (ND->isAnonymousNamespace())
172 return true;
173 } while ((DC = DC->getParent()));
174
175 return false;
176}
177
178TranslationUnitDecl *Decl::getTranslationUnitDecl() {
179 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
180 return TUD;
181
182 DeclContext *DC = getDeclContext();
183 assert(DC && "This decl is not contained in a translation unit!");
184
185 while (!DC->isTranslationUnit()) {
186 DC = DC->getParent();
187 assert(DC && "This decl is not contained in a translation unit!");
188 }
189
190 return cast<TranslationUnitDecl>(DC);
191}
192
193ASTContext &Decl::getASTContext() const {
194 return getTranslationUnitDecl()->getASTContext();
195}
196
197unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
198 switch (DeclKind) {
199 case Function:
200 case CXXMethod:
201 case CXXConstructor:
202 case CXXDestructor:
203 case CXXConversion:
204 case Typedef:
205 case EnumConstant:
206 case Var:
207 case ImplicitParam:
208 case ParmVar:
209 case NonTypeTemplateParm:
210 case ObjCMethod:
211 case ObjCContainer:
212 case ObjCInterface:
213 case ObjCProperty:
214 case ObjCCompatibleAlias:
215 return IDNS_Ordinary;
216
217 case UsingShadow:
218 return 0; // we'll actually overwrite this later
219
220 case UnresolvedUsingValue:
221 case UnresolvedUsingTypename:
222 return IDNS_Ordinary | IDNS_Using;
223
224 case Using:
225 return IDNS_Using;
226
227 case ObjCProtocol:
228 return IDNS_ObjCProtocol;
229
230 case ObjCImplementation:
231 return IDNS_ObjCImplementation;
232
233 case ObjCCategory:
234 case ObjCCategoryImpl:
235 return IDNS_ObjCCategoryName;
236
237 case Field:
238 case ObjCAtDefsField:
239 case ObjCIvar:
240 return IDNS_Member;
241
242 case Record:
243 case CXXRecord:
244 case Enum:
245 case TemplateTypeParm:
246 return IDNS_Tag;
247
248 case Namespace:
249 case Template:
250 case FunctionTemplate:
251 case ClassTemplate:
252 case TemplateTemplateParm:
253 case NamespaceAlias:
254 return IDNS_Tag | IDNS_Ordinary;
255
256 // Never have names.
257 case Friend:
258 case FriendTemplate:
259 case LinkageSpec:
260 case FileScopeAsm:
261 case StaticAssert:
262 case ObjCClass:
263 case ObjCPropertyImpl:
264 case ObjCForwardProtocol:
265 case Block:
266 case TranslationUnit:
267
268 // Aren't looked up?
269 case UsingDirective:
270 case ClassTemplateSpecialization:
271 case ClassTemplatePartialSpecialization:
272 return 0;
273 }
274
275 return 0;
276}
277
278void Decl::addAttr(Attr *NewAttr) {
279 Attr *&ExistingAttr = getASTContext().getDeclAttrs(this);
280
281 NewAttr->setNext(ExistingAttr);
282 ExistingAttr = NewAttr;
283
284 HasAttrs = true;
285}
286
287void Decl::invalidateAttrs() {
288 if (!HasAttrs) return;
289
290 HasAttrs = false;
291 getASTContext().eraseDeclAttrs(this);
292}
293
294const Attr *Decl::getAttrsImpl() const {
295 assert(HasAttrs && "getAttrs() should verify this!");
296 return getASTContext().getDeclAttrs(this);
297}
298
299void Decl::swapAttrs(Decl *RHS) {
300 bool HasLHSAttr = this->HasAttrs;
301 bool HasRHSAttr = RHS->HasAttrs;
302
303 // Usually, neither decl has attrs, nothing to do.
304 if (!HasLHSAttr && !HasRHSAttr) return;
305
306 // If 'this' has no attrs, swap the other way.
307 if (!HasLHSAttr)
308 return RHS->swapAttrs(this);
309
310 ASTContext &Context = getASTContext();
311
312 // Handle the case when both decls have attrs.
313 if (HasRHSAttr) {
314 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
315 return;
316 }
317
318 // Otherwise, LHS has an attr and RHS doesn't.
319 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
320 Context.eraseDeclAttrs(this);
321 this->HasAttrs = false;
322 RHS->HasAttrs = true;
323}
324
325
326void Decl::Destroy(ASTContext &C) {
327 // Free attributes for this decl.
328 if (HasAttrs) {
329 C.getDeclAttrs(this)->Destroy(C);
330 invalidateAttrs();
331 HasAttrs = false;
332 }
333
334#if 0
335 // FIXME: Once ownership is fully understood, we can enable this code
336 if (DeclContext *DC = dyn_cast<DeclContext>(this))
337 DC->decls_begin()->Destroy(C);
338
339 // Observe the unrolled recursion. By setting N->NextDeclInContext = 0x0
340 // within the loop, only the Destroy method for the first Decl
341 // will deallocate all of the Decls in a chain.
342
343 Decl* N = getNextDeclInContext();
344
345 while (N) {
346 Decl* Tmp = N->getNextDeclInContext();
347 N->NextDeclInContext = 0;
348 N->Destroy(C);
349 N = Tmp;
350 }
351
352 if (isOutOfSemaDC())
353 delete (C) getMultipleDC();
354
355 this->~Decl();
356 C.Deallocate((void *)this);
357#endif
358}
359
360Decl *Decl::castFromDeclContext (const DeclContext *D) {
361 Decl::Kind DK = D->getDeclKind();
362 switch(DK) {
363#define DECL_CONTEXT(Name) \
364 case Decl::Name: \
365 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
366#define DECL_CONTEXT_BASE(Name)
367#include "clang/AST/DeclNodes.def"
368 default:
369#define DECL_CONTEXT_BASE(Name) \
370 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
371 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
372#include "clang/AST/DeclNodes.def"
373 assert(false && "a decl that inherits DeclContext isn't handled");
374 return 0;
375 }
376}
377
378DeclContext *Decl::castToDeclContext(const Decl *D) {
379 Decl::Kind DK = D->getKind();
380 switch(DK) {
381#define DECL_CONTEXT(Name) \
382 case Decl::Name: \
383 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
384#define DECL_CONTEXT_BASE(Name)
385#include "clang/AST/DeclNodes.def"
386 default:
387#define DECL_CONTEXT_BASE(Name) \
388 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
389 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
390#include "clang/AST/DeclNodes.def"
391 assert(false && "a decl that inherits DeclContext isn't handled");
392 return 0;
393 }
394}
395
396CompoundStmt* Decl::getCompoundBody() const {
397 return dyn_cast_or_null<CompoundStmt>(getBody());
398}
399
400SourceLocation Decl::getBodyRBrace() const {
401 Stmt *Body = getBody();
402 if (!Body)
403 return SourceLocation();
404 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Body))
405 return CS->getRBracLoc();
406 assert(isa<CXXTryStmt>(Body) &&
407 "Body can only be CompoundStmt or CXXTryStmt");
408 return cast<CXXTryStmt>(Body)->getSourceRange().getEnd();
409}
410
411#ifndef NDEBUG
412void Decl::CheckAccessDeclContext() const {
413 // Suppress this check if any of the following hold:
414 // 1. this is the translation unit (and thus has no parent)
415 // 2. this is a template parameter (and thus doesn't belong to its context)
416 // 3. this is a ParmVarDecl (which can be in a record context during
417 // the brief period between its creation and the creation of the
418 // FunctionDecl)
419 // 4. the context is not a record
420 if (isa<TranslationUnitDecl>(this) ||
421 !isa<CXXRecordDecl>(getDeclContext()))
422 return;
423
424 assert(Access != AS_none &&
425 "Access specifier is AS_none inside a record decl");
426}
427
428#endif
429
430//===----------------------------------------------------------------------===//
431// DeclContext Implementation
432//===----------------------------------------------------------------------===//
433
434bool DeclContext::classof(const Decl *D) {
435 switch (D->getKind()) {
436#define DECL_CONTEXT(Name) case Decl::Name:
437#define DECL_CONTEXT_BASE(Name)
438#include "clang/AST/DeclNodes.def"
439 return true;
440 default:
441#define DECL_CONTEXT_BASE(Name) \
442 if (D->getKind() >= Decl::Name##First && \
443 D->getKind() <= Decl::Name##Last) \
444 return true;
445#include "clang/AST/DeclNodes.def"
446 return false;
447 }
448}
449
450DeclContext::~DeclContext() {
451 delete static_cast<StoredDeclsMap*>(LookupPtr);
452}
453
454void DeclContext::DestroyDecls(ASTContext &C) {
455 for (decl_iterator D = decls_begin(); D != decls_end(); )
456 (*D++)->Destroy(C);
457}
458
459/// \brief Find the parent context of this context that will be
460/// used for unqualified name lookup.
461///
462/// Generally, the parent lookup context is the semantic context. However, for
463/// a friend function the parent lookup context is the lexical context, which
464/// is the class in which the friend is declared.
465DeclContext *DeclContext::getLookupParent() {
466 // FIXME: Find a better way to identify friends
467 if (isa<FunctionDecl>(this))
468 if (getParent()->getLookupContext()->isFileContext() &&
469 getLexicalParent()->getLookupContext()->isRecord())
470 return getLexicalParent();
471
472 return getParent();
473}
474
475bool DeclContext::isDependentContext() const {
476 if (isFileContext())
477 return false;
478
479 if (isa<ClassTemplatePartialSpecializationDecl>(this))
480 return true;
481
482 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
483 if (Record->getDescribedClassTemplate())
484 return true;
485
486 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this))
487 if (Function->getDescribedFunctionTemplate())
488 return true;
489
490 return getParent() && getParent()->isDependentContext();
491}
492
493bool DeclContext::isTransparentContext() const {
494 if (DeclKind == Decl::Enum)
495 return true; // FIXME: Check for C++0x scoped enums
496 else if (DeclKind == Decl::LinkageSpec)
497 return true;
498 else if (DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast)
499 return cast<RecordDecl>(this)->isAnonymousStructOrUnion();
500 else if (DeclKind == Decl::Namespace)
501 return false; // FIXME: Check for C++0x inline namespaces
502
503 return false;
504}
505
506bool DeclContext::Encloses(DeclContext *DC) {
507 if (getPrimaryContext() != this)
508 return getPrimaryContext()->Encloses(DC);
509
510 for (; DC; DC = DC->getParent())
511 if (DC->getPrimaryContext() == this)
512 return true;
513 return false;
514}
515
516DeclContext *DeclContext::getPrimaryContext() {
517 switch (DeclKind) {
518 case Decl::TranslationUnit:
519 case Decl::LinkageSpec:
520 case Decl::Block:
521 // There is only one DeclContext for these entities.
522 return this;
523
524 case Decl::Namespace:
525 // The original namespace is our primary context.
526 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
527
528 case Decl::ObjCMethod:
529 return this;
530
531 case Decl::ObjCInterface:
532 case Decl::ObjCProtocol:
533 case Decl::ObjCCategory:
534 // FIXME: Can Objective-C interfaces be forward-declared?
535 return this;
536
537 case Decl::ObjCImplementation:
538 case Decl::ObjCCategoryImpl:
539 return this;
540
541 default:
542 if (DeclKind >= Decl::TagFirst && DeclKind <= Decl::TagLast) {
543 // If this is a tag type that has a definition or is currently
544 // being defined, that definition is our primary context.
545 if (const TagType *TagT =cast<TagDecl>(this)->TypeForDecl->getAs<TagType>())
546 if (TagT->isBeingDefined() ||
547 (TagT->getDecl() && TagT->getDecl()->isDefinition()))
548 return TagT->getDecl();
549 return this;
550 }
551
552 assert(DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast &&
553 "Unknown DeclContext kind");
554 return this;
555 }
556}
557
558DeclContext *DeclContext::getNextContext() {
559 switch (DeclKind) {
560 case Decl::Namespace:
561 // Return the next namespace
562 return static_cast<NamespaceDecl*>(this)->getNextNamespace();
563
564 default:
565 return 0;
566 }
567}
568
569/// \brief Load the declarations within this lexical storage from an
570/// external source.
571void
572DeclContext::LoadLexicalDeclsFromExternalStorage() const {
573 ExternalASTSource *Source = getParentASTContext().getExternalSource();
574 assert(hasExternalLexicalStorage() && Source && "No external storage?");
575
576 llvm::SmallVector<uint32_t, 64> Decls;
577 if (Source->ReadDeclsLexicallyInContext(const_cast<DeclContext *>(this),
578 Decls))
579 return;
580
581 // There is no longer any lexical storage in this context
582 ExternalLexicalStorage = false;
583
584 if (Decls.empty())
585 return;
586
587 // Resolve all of the declaration IDs into declarations, building up
588 // a chain of declarations via the Decl::NextDeclInContext field.
589 Decl *FirstNewDecl = 0;
590 Decl *PrevDecl = 0;
591 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
592 Decl *D = Source->GetDecl(Decls[I]);
593 if (PrevDecl)
594 PrevDecl->NextDeclInContext = D;
595 else
596 FirstNewDecl = D;
597
598 PrevDecl = D;
599 }
600
601 // Splice the newly-read declarations into the beginning of the list
602 // of declarations.
603 PrevDecl->NextDeclInContext = FirstDecl;
604 FirstDecl = FirstNewDecl;
605 if (!LastDecl)
606 LastDecl = PrevDecl;
607}
608
609void
610DeclContext::LoadVisibleDeclsFromExternalStorage() const {
611 DeclContext *This = const_cast<DeclContext *>(this);
612 ExternalASTSource *Source = getParentASTContext().getExternalSource();
613 assert(hasExternalVisibleStorage() && Source && "No external storage?");
614
615 llvm::SmallVector<VisibleDeclaration, 64> Decls;
616 if (Source->ReadDeclsVisibleInContext(This, Decls))
617 return;
618
619 // There is no longer any visible storage in this context
620 ExternalVisibleStorage = false;
621
622 // Load the declaration IDs for all of the names visible in this
623 // context.
624 assert(!LookupPtr && "Have a lookup map before de-serialization?");
625 StoredDeclsMap *Map = new StoredDeclsMap;
626 LookupPtr = Map;
627 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
628 (*Map)[Decls[I].Name].setFromDeclIDs(Decls[I].Declarations);
629 }
630}
631
632DeclContext::decl_iterator DeclContext::decls_begin() const {
633 if (hasExternalLexicalStorage())
634 LoadLexicalDeclsFromExternalStorage();
635
636 // FIXME: Check whether we need to load some declarations from
637 // external storage.
638 return decl_iterator(FirstDecl);
639}
640
641DeclContext::decl_iterator DeclContext::decls_end() const {
642 if (hasExternalLexicalStorage())
643 LoadLexicalDeclsFromExternalStorage();
644
645 return decl_iterator();
646}
647
648bool DeclContext::decls_empty() const {
649 if (hasExternalLexicalStorage())
650 LoadLexicalDeclsFromExternalStorage();
651
652 return !FirstDecl;
653}
654
655void DeclContext::removeDecl(Decl *D) {
656 assert(D->getLexicalDeclContext() == this &&
657 "decl being removed from non-lexical context");
658 assert((D->NextDeclInContext || D == LastDecl) &&
659 "decl is not in decls list");
660
661 // Remove D from the decl chain. This is O(n) but hopefully rare.
662 if (D == FirstDecl) {
663 if (D == LastDecl)
664 FirstDecl = LastDecl = 0;
665 else
666 FirstDecl = D->NextDeclInContext;
667 } else {
668 for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
669 assert(I && "decl not found in linked list");
670 if (I->NextDeclInContext == D) {
671 I->NextDeclInContext = D->NextDeclInContext;
672 if (D == LastDecl) LastDecl = I;
673 break;
674 }
675 }
676 }
677
678 // Mark that D is no longer in the decl chain.
679 D->NextDeclInContext = 0;
680
681 // Remove D from the lookup table if necessary.
682 if (isa<NamedDecl>(D)) {
683 NamedDecl *ND = cast<NamedDecl>(D);
684
685 void *OpaqueMap = getPrimaryContext()->LookupPtr;
686 if (!OpaqueMap) return;
687
688 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(OpaqueMap);
689 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
690 assert(Pos != Map->end() && "no lookup entry for decl");
691 Pos->second.remove(ND);
692 }
693}
694
695void DeclContext::addHiddenDecl(Decl *D) {
696 assert(D->getLexicalDeclContext() == this &&
697 "Decl inserted into wrong lexical context");
698 assert(!D->getNextDeclInContext() && D != LastDecl &&
699 "Decl already inserted into a DeclContext");
700
701 if (FirstDecl) {
702 LastDecl->NextDeclInContext = D;
703 LastDecl = D;
704 } else {
705 FirstDecl = LastDecl = D;
706 }
707}
708
709void DeclContext::addDecl(Decl *D) {
710 addHiddenDecl(D);
711
712 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
713 ND->getDeclContext()->makeDeclVisibleInContext(ND);
714}
715
716/// buildLookup - Build the lookup data structure with all of the
717/// declarations in DCtx (and any other contexts linked to it or
718/// transparent contexts nested within it).
719void DeclContext::buildLookup(DeclContext *DCtx) {
720 for (; DCtx; DCtx = DCtx->getNextContext()) {
721 for (decl_iterator D = DCtx->decls_begin(),
722 DEnd = DCtx->decls_end();
723 D != DEnd; ++D) {
724 // Insert this declaration into the lookup structure, but only
725 // if it's semantically in its decl context. During non-lazy
726 // lookup building, this is implicitly enforced by addDecl.
727 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
728 if (D->getDeclContext() == DCtx)
729 makeDeclVisibleInContextImpl(ND);
730
731 // Insert any forward-declared Objective-C interfaces into the lookup
732 // data structure.
733 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
734 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
735 I != IEnd; ++I)
736 makeDeclVisibleInContextImpl(I->getInterface());
737
738 // If this declaration is itself a transparent declaration context,
739 // add its members (recursively).
740 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
741 if (InnerCtx->isTransparentContext())
742 buildLookup(InnerCtx->getPrimaryContext());
743 }
744 }
745}
746
747DeclContext::lookup_result
748DeclContext::lookup(DeclarationName Name) {
749 DeclContext *PrimaryContext = getPrimaryContext();
750 if (PrimaryContext != this)
751 return PrimaryContext->lookup(Name);
752
753 if (hasExternalVisibleStorage())
754 LoadVisibleDeclsFromExternalStorage();
755
756 /// If there is no lookup data structure, build one now by walking
757 /// all of the linked DeclContexts (in declaration order!) and
758 /// inserting their values.
759 if (!LookupPtr) {
760 buildLookup(this);
761
762 if (!LookupPtr)
763 return lookup_result(0, 0);
764 }
765
766 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(LookupPtr);
767 StoredDeclsMap::iterator Pos = Map->find(Name);
768 if (Pos == Map->end())
769 return lookup_result(0, 0);
770 return Pos->second.getLookupResult(getParentASTContext());
771}
772
773DeclContext::lookup_const_result
774DeclContext::lookup(DeclarationName Name) const {
775 return const_cast<DeclContext*>(this)->lookup(Name);
776}
777
778DeclContext *DeclContext::getLookupContext() {
779 DeclContext *Ctx = this;
780 // Skip through transparent contexts.
781 while (Ctx->isTransparentContext())
782 Ctx = Ctx->getParent();
783 return Ctx;
784}
785
786DeclContext *DeclContext::getEnclosingNamespaceContext() {
787 DeclContext *Ctx = this;
788 // Skip through non-namespace, non-translation-unit contexts.
789 while (!Ctx->isFileContext() || Ctx->isTransparentContext())
790 Ctx = Ctx->getParent();
791 return Ctx->getPrimaryContext();
792}
793
794void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
795 // FIXME: This feels like a hack. Should DeclarationName support
796 // template-ids, or is there a better way to keep specializations
797 // from being visible?
798 if (isa<ClassTemplateSpecializationDecl>(D))
799 return;
800 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
801 if (FD->isFunctionTemplateSpecialization())
802 return;
803
804 DeclContext *PrimaryContext = getPrimaryContext();
805 if (PrimaryContext != this) {
806 PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
807 return;
808 }
809
810 // If we already have a lookup data structure, perform the insertion
811 // into it. Otherwise, be lazy and don't build that structure until
812 // someone asks for it.
813 if (LookupPtr || !Recoverable)
814 makeDeclVisibleInContextImpl(D);
815
816 // If we are a transparent context, insert into our parent context,
817 // too. This operation is recursive.
818 if (isTransparentContext())
819 getParent()->makeDeclVisibleInContext(D, Recoverable);
820}
821
822void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
823 // Skip unnamed declarations.
824 if (!D->getDeclName())
825 return;
826
827 // FIXME: This feels like a hack. Should DeclarationName support
828 // template-ids, or is there a better way to keep specializations
829 // from being visible?
830 if (isa<ClassTemplateSpecializationDecl>(D))
831 return;
832
833 if (!LookupPtr)
834 LookupPtr = new StoredDeclsMap;
835
836 // Insert this declaration into the map.
837 StoredDeclsMap &Map = *static_cast<StoredDeclsMap*>(LookupPtr);
838 StoredDeclsList &DeclNameEntries = Map[D->getDeclName()];
839 if (DeclNameEntries.isNull()) {
840 DeclNameEntries.setOnlyValue(D);
841 return;
842 }
843
844 // If it is possible that this is a redeclaration, check to see if there is
845 // already a decl for which declarationReplaces returns true. If there is
846 // one, just replace it and return.
847 if (DeclNameEntries.HandleRedeclaration(getParentASTContext(), D))
848 return;
849
850 // Put this declaration into the appropriate slot.
851 DeclNameEntries.AddSubsequentDecl(D);
852}
853
854/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
855/// this context.
856DeclContext::udir_iterator_range
857DeclContext::getUsingDirectives() const {
858 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
859 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
860 reinterpret_cast<udir_iterator>(Result.second));
861}
862
863void StoredDeclsList::materializeDecls(ASTContext &Context) {
864 if (isNull())
865 return;
866
867 switch ((DataKind)(Data & 0x03)) {
868 case DK_Decl:
869 case DK_Decl_Vector:
870 break;
871
872 case DK_DeclID: {
873 // Resolve this declaration ID to an actual declaration by
874 // querying the external AST source.
875 unsigned DeclID = Data >> 2;
876
877 ExternalASTSource *Source = Context.getExternalSource();
878 assert(Source && "No external AST source available!");
879
880 Data = reinterpret_cast<uintptr_t>(Source->GetDecl(DeclID));
881 break;
882 }
883
884 case DK_ID_Vector: {
885 // We have a vector of declaration IDs. Resolve all of them to
886 // actual declarations.
887 VectorTy &Vector = *getAsVector();
888 ExternalASTSource *Source = Context.getExternalSource();
889 assert(Source && "No external AST source available!");
890
891 for (unsigned I = 0, N = Vector.size(); I != N; ++I)
892 Vector[I] = reinterpret_cast<uintptr_t>(Source->GetDecl(Vector[I]));
893
894 Data = (Data & ~0x03) | DK_Decl_Vector;
895 break;
896 }
897 }
898}