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