DeclBase.h revision 6b3945f4bc757bdadd3e443180cf32c2cccb52a0
1//===-- DeclBase.h - Base Classes for representing declarations *- C++ -*-===//
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 defines the Decl and DeclContext interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLBASE_H
15#define LLVM_CLANG_AST_DECLBASE_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Type.h"
19#include "clang/Basic/SourceLocation.h"
20#include "llvm/ADT/PointerIntPair.h"
21#include <vector>
22
23namespace clang {
24class DeclContext;
25class TranslationUnitDecl;
26class NamespaceDecl;
27class NamedDecl;
28class ScopedDecl;
29class FunctionDecl;
30class CXXRecordDecl;
31class EnumDecl;
32class ObjCMethodDecl;
33class ObjCInterfaceDecl;
34class LinkageSpecDecl;
35class BlockDecl;
36class DeclarationName;
37
38/// Decl - This represents one declaration (or definition), e.g. a variable,
39/// typedef, function, struct, etc.
40///
41class Decl {
42public:
43  enum Kind {
44    // This lists the concrete classes of Decl in order of the inheritance
45    // hierarchy.  This allows us to do efficient classof tests based on the
46    // enums below.   The commented out names are abstract class names.
47    // [DeclContext] indicates that the class also inherits from DeclContext.
48
49    // Decl
50         TranslationUnit,  // [DeclContext]
51    //   NamedDecl
52    //     ObjCContainerDecl
53             ObjCCategory,
54             ObjCProtocol,
55             ObjCInterface,  // [DeclContext]
56           OverloadedFunction,
57           ObjCCategoryImpl,
58           ObjCImplementation,
59           ObjCMethod,  // [DeclContext]
60           ObjCProperty,
61    //     ScopedDecl
62             Field,
63               ObjCIvar,
64               ObjCAtDefsField,
65             Namespace,  // [DeclContext]
66    //       TypeDecl
67               Typedef,
68    //         TagDecl
69                 Enum,  // [DeclContext]
70                 Record, // [DeclContext]
71                   CXXRecord,
72 	       TemplateTypeParm,
73    //       ValueDecl
74               EnumConstant,
75               Function,  // [DeclContext]
76                 CXXMethod,
77                   CXXConstructor,
78                   CXXDestructor,
79                   CXXConversion,
80               Var,
81                 ImplicitParam,
82                 CXXClassVar,
83                 ParmVar,
84                   OriginalParmVar,
85  	         NonTypeTemplateParm,
86             LinkageSpec, // [DeclContext]
87           ObjCCompatibleAlias,
88           ObjCClass,
89           ObjCForwardProtocol,
90           ObjCPropertyImpl,
91         FileScopeAsm,
92	     Block, // [DeclContext]
93
94    // For each non-leaf class, we now define a mapping to the first/last member
95    // of the class, to allow efficient classof.
96    NamedFirst     = OverloadedFunction , NamedLast     = NonTypeTemplateParm,
97    FieldFirst     = Field        , FieldLast     = ObjCAtDefsField,
98    ScopedFirst    = Field        , ScopedLast    = LinkageSpec,
99    TypeFirst      = Typedef      , TypeLast      = TemplateTypeParm,
100    TagFirst       = Enum         , TagLast       = CXXRecord,
101    RecordFirst    = Record       , RecordLast    = CXXRecord,
102    ValueFirst     = EnumConstant , ValueLast     = NonTypeTemplateParm,
103    FunctionFirst  = Function     , FunctionLast  = CXXConversion,
104    VarFirst       = Var          , VarLast       = NonTypeTemplateParm
105  };
106
107  /// IdentifierNamespace - According to C99 6.2.3, there are four namespaces,
108  /// labels, tags, members and ordinary identifiers. These are meant
109  /// as bitmasks, so that searches in C++ can look into the "tag" namespace
110  /// during ordinary lookup.
111  enum IdentifierNamespace {
112    IDNS_Label = 0x1,
113    IDNS_Tag = 0x2,
114    IDNS_Member = 0x4,
115    IDNS_Ordinary = 0x8
116  };
117
118  /// ObjCDeclQualifier - Qualifier used on types in method declarations
119  /// for remote messaging. They are meant for the arguments though and
120  /// applied to the Decls (ObjCMethodDecl and ParmVarDecl).
121  enum ObjCDeclQualifier {
122    OBJC_TQ_None = 0x0,
123    OBJC_TQ_In = 0x1,
124    OBJC_TQ_Inout = 0x2,
125    OBJC_TQ_Out = 0x4,
126    OBJC_TQ_Bycopy = 0x8,
127    OBJC_TQ_Byref = 0x10,
128    OBJC_TQ_Oneway = 0x20
129  };
130
131private:
132  /// Loc - The location that this decl.
133  SourceLocation Loc;
134
135  /// DeclKind - This indicates which class this is.
136  Kind DeclKind   :  8;
137
138  /// InvalidDecl - This indicates a semantic error occurred.
139  unsigned int InvalidDecl :  1;
140
141  /// HasAttrs - This indicates whether the decl has attributes or not.
142  unsigned int HasAttrs : 1;
143
144  /// Implicit - Whether this declaration was implicitly generated by
145  /// the implementation rather than explicitly written by the user.
146  bool Implicit : 1;
147
148 protected:
149  /// Access - Used by C++ decls for the access specifier.
150  // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
151  unsigned Access : 2;
152  friend class CXXClassMemberWrapper;
153
154  Decl(Kind DK, SourceLocation L) : Loc(L), DeclKind(DK), InvalidDecl(0),
155    HasAttrs(false) {
156    if (Decl::CollectingStats()) addDeclKind(DK);
157  }
158
159  virtual ~Decl();
160
161public:
162  SourceLocation getLocation() const { return Loc; }
163  void setLocation(SourceLocation L) { Loc = L; }
164
165  Kind getKind() const { return DeclKind; }
166  const char *getDeclKindName() const;
167
168  void addAttr(Attr *attr);
169  const Attr *getAttrs() const;
170  void swapAttrs(Decl *D);
171  void invalidateAttrs();
172
173  template<typename T> const T *getAttr() const {
174    for (const Attr *attr = getAttrs(); attr; attr = attr->getNext())
175      if (const T *V = dyn_cast<T>(attr))
176        return V;
177
178    return 0;
179  }
180
181  /// setInvalidDecl - Indicates the Decl had a semantic error. This
182  /// allows for graceful error recovery.
183  void setInvalidDecl() { InvalidDecl = 1; }
184  bool isInvalidDecl() const { return (bool) InvalidDecl; }
185
186  /// isImplicit - Indicates whether the declaration was implicitly
187  /// generated by the implementation. If false, this declaration
188  /// was written explicitly in the source code.
189  bool isImplicit() const { return Implicit; }
190  void setImplicit(bool I = true) { Implicit = I; }
191
192  IdentifierNamespace getIdentifierNamespace() const {
193    switch (DeclKind) {
194    default:
195      if (DeclKind >= FunctionFirst && DeclKind <= FunctionLast)
196        return IDNS_Ordinary;
197      assert(0 && "Unknown decl kind!");
198    case ImplicitParam:
199    case Typedef:
200    case Var:
201    case ParmVar:
202    case OriginalParmVar:
203    case EnumConstant:
204    case NonTypeTemplateParm:
205    case Field:
206    case ObjCAtDefsField:
207    case ObjCIvar:
208    case ObjCInterface:
209    case ObjCCompatibleAlias:
210    case OverloadedFunction:
211    case CXXMethod:
212    case CXXConversion:
213    case CXXClassVar:
214      return IDNS_Ordinary;
215    case Record:
216    case CXXRecord:
217    case TemplateTypeParm:
218    case Enum:
219      return IDNS_Tag;
220    case Namespace:
221      return IdentifierNamespace(IDNS_Tag | IDNS_Ordinary);
222    }
223  }
224
225  bool isInIdentifierNamespace(unsigned NS) const {
226    return getIdentifierNamespace() & NS;
227  }
228
229  // getBody - If this Decl represents a declaration for a body of code,
230  //  such as a function or method definition, this method returns the top-level
231  //  Stmt* of that body.  Otherwise this method returns null.
232  virtual Stmt* getBody() const { return 0; }
233
234  // global temp stats (until we have a per-module visitor)
235  static void addDeclKind(Kind k);
236  static bool CollectingStats(bool Enable = false);
237  static void PrintStats();
238
239  /// isTemplateParameter - Determines whether this declartion is a
240  /// template parameter.
241  bool isTemplateParameter() const;
242
243  // Implement isa/cast/dyncast/etc.
244  static bool classof(const Decl *) { return true; }
245  static DeclContext *castToDeclContext(const Decl *);
246  static Decl *castFromDeclContext(const DeclContext *);
247
248  /// Emit - Serialize this Decl to Bitcode.
249  void Emit(llvm::Serializer& S) const;
250
251  /// Create - Deserialize a Decl from Bitcode.
252  static Decl* Create(llvm::Deserializer& D, ASTContext& C);
253
254  /// Destroy - Call destructors and release memory.
255  virtual void Destroy(ASTContext& C);
256
257protected:
258  /// EmitImpl - Provides the subclass-specific serialization logic for
259  ///   serializing out a decl.
260  virtual void EmitImpl(llvm::Serializer& S) const {
261    // FIXME: This will eventually be a pure virtual function.
262    assert (false && "Not implemented.");
263  }
264
265  void EmitInRec(llvm::Serializer& S) const;
266  void ReadInRec(llvm::Deserializer& D, ASTContext& C);
267};
268
269/// DeclContext - This is used only as base class of specific decl types that
270/// can act as declaration contexts. These decls are:
271///
272///   TranslationUnitDecl
273///   NamespaceDecl
274///   FunctionDecl
275///   RecordDecl/CXXRecordDecl
276///   EnumDecl
277///   ObjCMethodDecl
278///   ObjCInterfaceDecl
279///   LinkageSpecDecl
280///   BlockDecl
281class DeclContext {
282  /// DeclKind - This indicates which class this is.
283  Decl::Kind DeclKind   :  8;
284
285  /// LookupPtrKind - Describes what kind of pointer LookupPtr
286  /// actually is.
287  enum LookupPtrKind {
288    /// LookupIsMap - Indicates that LookupPtr is actually a map.
289    LookupIsMap = 7
290  };
291
292  /// LookupPtr - Pointer to a data structure used to lookup
293  /// declarations within this context. If the context contains fewer
294  /// than seven declarations, the number of declarations is provided
295  /// in the 3 lowest-order bits and the upper bits are treated as a
296  /// pointer to an array of ScopedDecl pointers. If the context
297  /// contains seven or more declarations, the upper bits are treated
298  /// as a pointer to a DenseMap<DeclarationName, std::vector<ScopedDecl>>.
299  /// FIXME: We need a better data structure for this.
300  llvm::PointerIntPair<void*, 3> LookupPtr;
301
302  /// Decls - Contains all of the declarations that are defined inside
303  /// this declaration context.
304  std::vector<ScopedDecl*> Decls;
305
306  // Used in the CastTo template to get the DeclKind
307  // from a Decl or a DeclContext. DeclContext doesn't have a getKind() method
308  // to avoid 'ambiguous access' compiler errors.
309  template<typename T> struct KindTrait {
310    static Decl::Kind getKind(const T *D) { return D->getKind(); }
311  };
312
313  // Used only by the ToDecl and FromDecl methods
314  template<typename To, typename From>
315  static To *CastTo(const From *D) {
316    Decl::Kind DK = KindTrait<From>::getKind(D);
317    switch(DK) {
318      case Decl::TranslationUnit:
319        return static_cast<TranslationUnitDecl*>(const_cast<From*>(D));
320      case Decl::Namespace:
321        return static_cast<NamespaceDecl*>(const_cast<From*>(D));
322      case Decl::Enum:
323        return static_cast<EnumDecl*>(const_cast<From*>(D));
324      case Decl::Record:
325        return static_cast<RecordDecl*>(const_cast<From*>(D));
326      case Decl::CXXRecord:
327        return static_cast<CXXRecordDecl*>(const_cast<From*>(D));
328      case Decl::ObjCMethod:
329        return static_cast<ObjCMethodDecl*>(const_cast<From*>(D));
330      case Decl::ObjCInterface:
331        return static_cast<ObjCInterfaceDecl*>(const_cast<From*>(D));
332      case Decl::LinkageSpec:
333        return static_cast<LinkageSpecDecl*>(const_cast<From*>(D));
334      case Decl::Block:
335        return static_cast<BlockDecl*>(const_cast<From*>(D));
336      default:
337        if (DK >= Decl::FunctionFirst && DK <= Decl::FunctionLast)
338          return static_cast<FunctionDecl*>(const_cast<From*>(D));
339
340        assert(false && "a decl that inherits DeclContext isn't handled");
341        return 0;
342    }
343  }
344
345  /// isLookupMap - Determine if the lookup structure is a
346  /// DenseMap. Othewise, it is an array.
347  bool isLookupMap() const { return LookupPtr.getInt() == LookupIsMap; }
348
349protected:
350  DeclContext(Decl::Kind K) : DeclKind(K), LookupPtr() {
351  }
352
353  void DestroyDecls(ASTContext &C);
354
355public:
356  ~DeclContext();
357
358  /// getParent - Returns the containing DeclContext if this is a ScopedDecl,
359  /// else returns NULL.
360  const DeclContext *getParent() const;
361  DeclContext *getParent() {
362    return const_cast<DeclContext*>(
363                             const_cast<const DeclContext*>(this)->getParent());
364  }
365
366  /// getLexicalParent - Returns the containing lexical DeclContext. May be
367  /// different from getParent, e.g.:
368  ///
369  ///   namespace A {
370  ///      struct S;
371  ///   }
372  ///   struct A::S {}; // getParent() == namespace 'A'
373  ///                   // getLexicalParent() == translation unit
374  ///
375  const DeclContext *getLexicalParent() const;
376  DeclContext *getLexicalParent() {
377    return const_cast<DeclContext*>(
378                      const_cast<const DeclContext*>(this)->getLexicalParent());
379  }
380
381  bool isFunctionOrMethod() const {
382    switch (DeclKind) {
383      case Decl::Block:
384      case Decl::ObjCMethod:
385        return true;
386
387      default:
388       if (DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast)
389         return true;
390        return false;
391    }
392  }
393
394  bool isFileContext() const {
395    return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
396  }
397
398  bool isRecord() const {
399    return DeclKind == Decl::Record || DeclKind == Decl::CXXRecord;
400  }
401
402  bool isNamespace() const {
403    return DeclKind == Decl::Namespace;
404  }
405
406  /// isTransparentContext - Determines whether this context is a
407  /// "transparent" context, meaning that the members declared in this
408  /// context are semantically declared in the nearest enclosing
409  /// non-transparent (opaque) context but are lexically declared in
410  /// this context. For example, consider the enumerators of an
411  /// enumeration type:
412  /// @code
413  /// enum E {
414  ///   Val1
415  /// };
416  /// @endcode
417  /// Here, E is a transparent context, so its enumerator (Val1) will
418  /// appear (semantically) that it is in the same context of E.
419  /// Examples of transparent contexts include: enumerations (except for
420  /// C++0x scoped enums), C++ linkage specifications, and C++0x
421  /// inline namespaces.
422  bool isTransparentContext() const;
423
424  bool Encloses(DeclContext *DC) const {
425    for (; DC; DC = DC->getParent())
426      if (DC == this)
427        return true;
428    return false;
429  }
430
431  /// getPrimaryContext - There may be many different
432  /// declarations of the same entity (including forward declarations
433  /// of classes, multiple definitions of namespaces, etc.), each with
434  /// a different set of declarations. This routine returns the
435  /// "primary" DeclContext structure, which will contain the
436  /// information needed to perform name lookup into this context.
437  DeclContext *getPrimaryContext(ASTContext &Context);
438
439  /// getLookupContext - Retrieve the innermost non-transparent
440  /// context of this context, which corresponds to the innermost
441  /// location from which name lookup can find the entities in this
442  /// context.
443  DeclContext *getLookupContext() {
444    return const_cast<DeclContext *>(
445             const_cast<const DeclContext *>(this)->getLookupContext());
446  }
447  const DeclContext *getLookupContext() const;
448
449  /// getNextContext - If this is a DeclContext that may have other
450  /// DeclContexts that are semantically connected but syntactically
451  /// different, such as C++ namespaces, this routine retrieves the
452  /// next DeclContext in the link. Iteration through the chain of
453  /// DeclContexts should begin at the primary DeclContext and
454  /// continue until this function returns NULL. For example, given:
455  /// @code
456  /// namespace N {
457  ///   int x;
458  /// }
459  /// namespace N {
460  ///   int y;
461  /// }
462  /// @endcode
463  /// The first occurrence of namespace N will be the primary
464  /// DeclContext. Its getNextContext will return the second
465  /// occurrence of namespace N.
466  DeclContext *getNextContext();
467
468  /// decl_iterator - Iterates through the declarations stored
469  /// within this context.
470  typedef std::vector<ScopedDecl*>::const_iterator decl_iterator;
471
472  /// decls_begin/decls_end - Iterate over the declarations stored in
473  /// this context.
474  decl_iterator decls_begin() const { return Decls.begin(); }
475  decl_iterator decls_end()   const { return Decls.end(); }
476
477  /// addDecl - Add the declaration D to this scope. Note that
478  /// declarations are added at the beginning of the declaration
479  /// chain, so reverseDeclChain() should be called after all
480  /// declarations have been added. If AllowLookup, also adds this
481  /// declaration into data structure for name lookup.
482  void addDecl(ASTContext &Context, ScopedDecl *D, bool AllowLookup = true);
483
484  void buildLookup(ASTContext &Context, DeclContext *DCtx);
485
486  /// lookup_iterator - An iterator that provides access to the results
487  /// of looking up a name within this context.
488  typedef ScopedDecl **lookup_iterator;
489
490  /// lookup_const_iterator - An iterator that provides non-mutable
491  /// access to the results of lookup up a name within this context.
492  typedef ScopedDecl * const * lookup_const_iterator;
493
494  typedef std::pair<lookup_iterator, lookup_iterator> lookup_result;
495  typedef std::pair<lookup_const_iterator, lookup_const_iterator>
496    lookup_const_result;
497
498  /// lookup - Find the declarations (if any) with the given Name in
499  /// this context. Returns a range of iterators that contains all of
500  /// the declarations with this name (which may be 0, 1, or 2
501  /// declarations). If two declarations are returned, the declaration
502  /// in the "ordinary" identifier namespace will precede the
503  /// declaration in the "tag" identifier namespace (e.g., values
504  /// before types). Note that this routine will not look into parent
505  /// contexts.
506  lookup_result lookup(ASTContext &Context, DeclarationName Name);
507  lookup_const_result lookup(ASTContext &Context, DeclarationName Name) const;
508
509  /// insert - Insert the declaration D into this context. Up to two
510  /// declarations with the same name can be inserted into a single
511  /// declaration context, one in the "tag" namespace (e.g., for
512  /// classes and enums) and one in the "ordinary" namespaces (e.g.,
513  /// for variables, functions, and other values). Note that, if there
514  /// is already a declaration with the same name and identifier
515  /// namespace, D will replace it. It is up to the caller to ensure
516  /// that this replacement is semantically correct, e.g., that
517  /// declarations are only replaced by later declarations of the same
518  /// entity and not a declaration of some other kind of entity.
519  void insert(ASTContext &Context, ScopedDecl *D);
520
521  static bool classof(const Decl *D) {
522    switch (D->getKind()) {
523      case Decl::TranslationUnit:
524      case Decl::Namespace:
525      case Decl::Enum:
526      case Decl::Record:
527      case Decl::CXXRecord:
528      case Decl::ObjCMethod:
529      case Decl::ObjCInterface:
530      case Decl::LinkageSpec:
531      case Decl::Block:
532        return true;
533      default:
534        if (D->getKind() >= Decl::FunctionFirst &&
535            D->getKind() <= Decl::FunctionLast)
536          return true;
537        return false;
538    }
539  }
540  static bool classof(const DeclContext *D) { return true; }
541  static bool classof(const TranslationUnitDecl *D) { return true; }
542  static bool classof(const NamespaceDecl *D) { return true; }
543  static bool classof(const FunctionDecl *D) { return true; }
544  static bool classof(const RecordDecl *D) { return true; }
545  static bool classof(const CXXRecordDecl *D) { return true; }
546  static bool classof(const EnumDecl *D) { return true; }
547  static bool classof(const ObjCMethodDecl *D) { return true; }
548  static bool classof(const ObjCInterfaceDecl *D) { return true; }
549  static bool classof(const LinkageSpecDecl *D) { return true; }
550  static bool classof(const BlockDecl *D) { return true; }
551
552private:
553  void insertImpl(ScopedDecl *D);
554
555  void EmitOutRec(llvm::Serializer& S) const;
556  void ReadOutRec(llvm::Deserializer& D, ASTContext& C);
557
558  friend class Decl;
559};
560
561template<> struct DeclContext::KindTrait<DeclContext> {
562  static Decl::Kind getKind(const DeclContext *D) { return D->DeclKind; }
563};
564
565inline bool Decl::isTemplateParameter() const {
566  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm;
567}
568
569
570} // end clang.
571
572namespace llvm {
573
574/// Implement a isa_impl_wrap specialization to check whether a DeclContext is
575/// a specific Decl.
576template<class ToTy>
577struct isa_impl_wrap<ToTy,
578                     const ::clang::DeclContext,const ::clang::DeclContext> {
579  static bool doit(const ::clang::DeclContext &Val) {
580    return ToTy::classof(::clang::Decl::castFromDeclContext(&Val));
581  }
582};
583template<class ToTy>
584struct isa_impl_wrap<ToTy, ::clang::DeclContext, ::clang::DeclContext>
585  : public isa_impl_wrap<ToTy,
586                      const ::clang::DeclContext,const ::clang::DeclContext> {};
587
588/// Implement cast_convert_val for Decl -> DeclContext conversions.
589template<class FromTy>
590struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
591  static ::clang::DeclContext &doit(const FromTy &Val) {
592    return *FromTy::castToDeclContext(&Val);
593  }
594};
595
596template<class FromTy>
597struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
598  static ::clang::DeclContext *doit(const FromTy *Val) {
599    return FromTy::castToDeclContext(Val);
600  }
601};
602
603template<class FromTy>
604struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
605  static const ::clang::DeclContext &doit(const FromTy &Val) {
606    return *FromTy::castToDeclContext(&Val);
607  }
608};
609
610template<class FromTy>
611struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
612  static const ::clang::DeclContext *doit(const FromTy *Val) {
613    return FromTy::castToDeclContext(Val);
614  }
615};
616
617/// Implement cast_convert_val for DeclContext -> Decl conversions.
618template<class ToTy>
619struct cast_convert_val<ToTy,
620                        const ::clang::DeclContext,const ::clang::DeclContext> {
621  static ToTy &doit(const ::clang::DeclContext &Val) {
622    return *reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(&Val));
623  }
624};
625template<class ToTy>
626struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext>
627  : public cast_convert_val<ToTy,
628                      const ::clang::DeclContext,const ::clang::DeclContext> {};
629
630template<class ToTy>
631struct cast_convert_val<ToTy,
632                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
633  static ToTy *doit(const ::clang::DeclContext *Val) {
634    return reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(Val));
635  }
636};
637template<class ToTy>
638struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*>
639  : public cast_convert_val<ToTy,
640                    const ::clang::DeclContext*,const ::clang::DeclContext*> {};
641
642} // end namespace llvm
643
644#endif
645