Decl.h revision 64650af7cc4352c6c67b9bd1bf8ef3ce7471b910
1//===--- Decl.h - 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 subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECL_H
15#define LLVM_CLANG_AST_DECL_H
16
17#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/OperatorKinds.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/Parse/AccessSpecifier.h"
22#include "llvm/ADT/SmallVector.h"
23
24namespace clang {
25class Expr;
26class Stmt;
27class CompoundStmt;
28class StringLiteral;
29
30/// TranslationUnitDecl - The top declaration context.
31/// FIXME: The TranslationUnit class should probably be modified to serve as
32/// the top decl context. It would have ownership of the top decls so that the
33/// AST is self-contained and easily de/serializable.
34/// FIXME: TranslationUnitDecl isn't really a Decl (!)
35class TranslationUnitDecl : public Decl, public DeclContext {
36  TranslationUnitDecl()
37    : Decl(TranslationUnit, 0, SourceLocation()),
38      DeclContext(TranslationUnit) {}
39public:
40  static TranslationUnitDecl *Create(ASTContext &C);
41  // Implement isa/cast/dyncast/etc.
42  static bool classof(const Decl *D) { return D->getKind() == TranslationUnit; }
43  static bool classof(const TranslationUnitDecl *D) { return true; }
44  static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
45    return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
46  }
47  static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
48    return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
49  }
50
51protected:
52  /// EmitImpl - Serialize this TranslationUnitDecl. Called by Decl::Emit.
53  virtual void EmitImpl(llvm::Serializer& S) const;
54
55  /// CreateImpl - Deserialize a TranslationUnitDecl.  Called by Decl::Create.
56  static TranslationUnitDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
57
58  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
59};
60
61/// NamedDecl - This represents a decl with a name.  Many decls have names such
62/// as ObjCMethodDecl, but not @class, etc.
63class NamedDecl : public Decl {
64  /// Name - The name of this declaration, which is typically a normal
65  /// identifier but may also be a special kind of name (C++
66  /// constructor, Objective-C selector, etc.)
67  DeclarationName Name;
68
69protected:
70  NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
71    : Decl(DK, DC, L), Name(N) {}
72
73  NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id)
74    : Decl(DK, DC, L), Name(Id) {}
75
76public:
77  /// getIdentifier - Get the identifier that names this declaration,
78  /// if there is one. This will return NULL if this declaration has
79  /// no name (e.g., for an unnamed class) or if the name is a special
80  /// name (C++ constructor, Objective-C selector, etc.).
81  IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
82
83  /// getNameAsCString - Get the name of identifier for this declaration as a
84  /// C string (const char*).  This requires that the declaration have a name
85  /// and that it be a simple identifier.
86  const char *getNameAsCString() const {
87    assert(getIdentifier() && "Name is not a simple identifier");
88    return getIdentifier()->getName();
89  }
90
91  /// getDeclName - Get the actual, stored name of the declaration,
92  /// which may be a special name.
93  DeclarationName getDeclName() const { return Name; }
94
95  /// getNameAsString - Get a human-readable name for the declaration, even if
96  /// it is one of the special kinds of names (C++ constructor, Objective-C
97  /// selector, etc).  Creating this name requires expensive string
98  /// manipulation, so it should be called only when performance doesn't matter.
99  /// For simple declarations, getNameAsCString() should suffice.
100  std::string getNameAsString() const { return Name.getAsString(); }
101
102  /// declarationReplaces - Determine whether this declaration, if
103  /// known to be well-formed within its context, will replace the
104  /// declaration OldD if introduced into scope. A declaration will
105  /// replace another declaration if, for example, it is a
106  /// redeclaration of the same variable or function, but not if it is
107  /// a declaration of a different kind (function vs. class) or an
108  /// overloaded function.
109  bool declarationReplaces(NamedDecl *OldD) const;
110
111  static bool classof(const Decl *D) {
112    return D->getKind() >= NamedFirst && D->getKind() <= NamedLast;
113  }
114  static bool classof(const NamedDecl *D) { return true; }
115
116protected:
117  void EmitInRec(llvm::Serializer& S) const;
118  void ReadInRec(llvm::Deserializer& D, ASTContext& C);
119};
120
121/// NamespaceDecl - Represent a C++ namespace.
122class NamespaceDecl : public NamedDecl, public DeclContext {
123  SourceLocation LBracLoc, RBracLoc;
124
125  // For extended namespace definitions:
126  //
127  // namespace A { int x; }
128  // namespace A { int y; }
129  //
130  // there will be one NamespaceDecl for each declaration.
131  // NextDeclarator points to the next extended declaration.
132  // OrigNamespace points to the original namespace declaration.
133  // OrigNamespace of the first namespace decl points to itself.
134
135  NamespaceDecl *OrigNamespace;
136
137  NamespaceDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id)
138    : NamedDecl(Namespace, DC, L, Id), DeclContext(Namespace) {
139      OrigNamespace = this;
140  }
141public:
142  static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
143                               SourceLocation L, IdentifierInfo *Id);
144
145  virtual void Destroy(ASTContext& C);
146
147  NamespaceDecl *getNextNamespace() {
148    return cast_or_null<NamespaceDecl>(getNextDeclarator());
149  }
150  const NamespaceDecl *getNextNamespace() const {
151    return cast_or_null<NamespaceDecl>(getNextDeclarator());
152  }
153  void setNextNamespace(NamespaceDecl *ND) { setNextDeclarator(ND); }
154
155  NamespaceDecl *getOriginalNamespace() const {
156    return OrigNamespace;
157  }
158  void setOriginalNamespace(NamespaceDecl *ND) { OrigNamespace = ND; }
159
160  SourceRange getSourceRange() const {
161    return SourceRange(LBracLoc, RBracLoc);
162  }
163
164  SourceLocation getLBracLoc() const { return LBracLoc; }
165  SourceLocation getRBracLoc() const { return RBracLoc; }
166  void setLBracLoc(SourceLocation LBrace) { LBracLoc = LBrace; }
167  void setRBracLoc(SourceLocation RBrace) { RBracLoc = RBrace; }
168
169  // Implement isa/cast/dyncast/etc.
170  static bool classof(const Decl *D) { return D->getKind() == Namespace; }
171  static bool classof(const NamespaceDecl *D) { return true; }
172  static DeclContext *castToDeclContext(const NamespaceDecl *D) {
173    return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
174  }
175  static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
176    return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
177  }
178
179protected:
180  /// EmitImpl - Serialize this NamespaceDecl. Called by Decl::Emit.
181  virtual void EmitImpl(llvm::Serializer& S) const;
182
183  /// CreateImpl - Deserialize a NamespaceDecl.  Called by Decl::Create.
184  static NamespaceDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
185
186  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
187};
188
189/// ValueDecl - Represent the declaration of a variable (in which case it is
190/// an lvalue) a function (in which case it is a function designator) or
191/// an enum constant.
192class ValueDecl : public NamedDecl {
193  QualType DeclType;
194
195protected:
196  ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
197            DeclarationName N, QualType T)
198    : NamedDecl(DK, DC, L, N), DeclType(T) {}
199public:
200  QualType getType() const { return DeclType; }
201  void setType(QualType newType) { DeclType = newType; }
202
203  // Implement isa/cast/dyncast/etc.
204  static bool classof(const Decl *D) {
205    return D->getKind() >= ValueFirst && D->getKind() <= ValueLast;
206  }
207  static bool classof(const ValueDecl *D) { return true; }
208
209protected:
210  void EmitInRec(llvm::Serializer& S) const;
211  void ReadInRec(llvm::Deserializer& D, ASTContext& C);
212};
213
214/// VarDecl - An instance of this class is created to represent a variable
215/// declaration or definition.
216class VarDecl : public ValueDecl {
217public:
218  enum StorageClass {
219    None, Auto, Register, Extern, Static, PrivateExtern
220  };
221private:
222  Stmt *Init;
223  // FIXME: This can be packed into the bitfields in Decl.
224  unsigned SClass : 3;
225  bool ThreadSpecified : 1;
226  bool HasCXXDirectInit : 1;
227
228  /// DeclaredInCondition - Whether this variable was declared in a
229  /// condition, e.g., if (int x = foo()) { ... }.
230  bool DeclaredInCondition : 1;
231
232  // Move to DeclGroup when it is implemented.
233  SourceLocation TypeSpecStartLoc;
234  friend class StmtIteratorBase;
235protected:
236  VarDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
237          QualType T, StorageClass SC, SourceLocation TSSL = SourceLocation())
238    : ValueDecl(DK, DC, L, Id, T), Init(0),
239          ThreadSpecified(false), HasCXXDirectInit(false),
240          DeclaredInCondition(false), TypeSpecStartLoc(TSSL) {
241    SClass = SC;
242  }
243public:
244  static VarDecl *Create(ASTContext &C, DeclContext *DC,
245                         SourceLocation L, IdentifierInfo *Id,
246                         QualType T, StorageClass S,
247                         SourceLocation TypeSpecStartLoc = SourceLocation());
248
249  virtual ~VarDecl();
250  virtual void Destroy(ASTContext& C);
251
252  StorageClass getStorageClass() const { return (StorageClass)SClass; }
253
254  SourceLocation getTypeSpecStartLoc() const { return TypeSpecStartLoc; }
255
256  const Expr *getInit() const { return (const Expr*) Init; }
257  Expr *getInit() { return (Expr*) Init; }
258  void setInit(Expr *I) { Init = (Stmt*) I; }
259
260  void setThreadSpecified(bool T) { ThreadSpecified = T; }
261  bool isThreadSpecified() const {
262    return ThreadSpecified;
263  }
264
265  void setCXXDirectInitializer(bool T) { HasCXXDirectInit = T; }
266
267  /// hasCXXDirectInitializer - If true, the initializer was a direct
268  /// initializer, e.g: "int x(1);". The Init expression will be the expression
269  /// inside the parens or a "ClassType(a,b,c)" class constructor expression for
270  /// class types. Clients can distinguish between "int x(1);" and "int x=1;"
271  /// by checking hasCXXDirectInitializer.
272  ///
273  bool hasCXXDirectInitializer() const {
274    return HasCXXDirectInit;
275  }
276
277  /// isDeclaredInCondition - Whether this variable was declared as
278  /// part of a condition in an if/switch/while statement, e.g.,
279  /// @code
280  /// if (int x = foo()) { ... }
281  /// @endcode
282  bool isDeclaredInCondition() const {
283    return DeclaredInCondition;
284  }
285  void setDeclaredInCondition(bool InCondition) {
286    DeclaredInCondition = InCondition;
287  }
288
289  /// hasLocalStorage - Returns true if a variable with function scope
290  ///  is a non-static local variable.
291  bool hasLocalStorage() const {
292    if (getStorageClass() == None)
293      return !isFileVarDecl();
294
295    // Return true for:  Auto, Register.
296    // Return false for: Extern, Static, PrivateExtern.
297
298    return getStorageClass() <= Register;
299  }
300
301  /// hasGlobalStorage - Returns true for all variables that do not
302  ///  have local storage.  This includs all global variables as well
303  ///  as static variables declared within a function.
304  bool hasGlobalStorage() const { return !hasLocalStorage(); }
305
306  /// isBlockVarDecl - Returns true for local variable declarations.  Note that
307  /// this includes static variables inside of functions.
308  ///
309  ///   void foo() { int x; static int y; extern int z; }
310  ///
311  bool isBlockVarDecl() const {
312    if (getKind() != Decl::Var)
313      return false;
314    if (const DeclContext *DC = getDeclContext())
315      return DC->getLookupContext()->isFunctionOrMethod();
316    return false;
317  }
318
319  /// isFileVarDecl - Returns true for file scoped variable declaration.
320  bool isFileVarDecl() const {
321    if (getKind() != Decl::Var)
322      return false;
323    if (const DeclContext *Ctx = getDeclContext()) {
324      Ctx = Ctx->getLookupContext();
325      if (isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx) )
326        return true;
327    }
328    return false;
329  }
330
331  // Implement isa/cast/dyncast/etc.
332  static bool classof(const Decl *D) {
333    return D->getKind() >= VarFirst && D->getKind() <= VarLast;
334  }
335  static bool classof(const VarDecl *D) { return true; }
336
337protected:
338  void EmitInRec(llvm::Serializer& S) const;
339  void ReadInRec(llvm::Deserializer& D, ASTContext& C);
340
341  void EmitOutRec(llvm::Serializer& S) const;
342  void ReadOutRec(llvm::Deserializer& D, ASTContext& C);
343
344  /// EmitImpl - Serialize this VarDecl. Called by Decl::Emit.
345  virtual void EmitImpl(llvm::Serializer& S) const;
346
347  /// ReadImpl - Deserialize this VarDecl. Called by subclasses.
348  virtual void ReadImpl(llvm::Deserializer& D, ASTContext& C);
349
350  /// CreateImpl - Deserialize a VarDecl.  Called by Decl::Create.
351  static VarDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
352};
353
354class ImplicitParamDecl : public VarDecl {
355protected:
356  ImplicitParamDecl(Kind DK, DeclContext *DC, SourceLocation L,
357            IdentifierInfo *Id, QualType Tw)
358    : VarDecl(DK, DC, L, Id, Tw, VarDecl::None) {}
359public:
360  static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
361                         SourceLocation L, IdentifierInfo *Id,
362                         QualType T);
363  // Implement isa/cast/dyncast/etc.
364  static bool classof(const ImplicitParamDecl *D) { return true; }
365  static bool classof(const Decl *D) { return D->getKind() == ImplicitParam; }
366};
367
368/// ParmVarDecl - Represent a parameter to a function.
369class ParmVarDecl : public VarDecl {
370  // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum
371  /// FIXME: Also can be paced into the bitfields in Decl.
372  /// in, inout, etc.
373  unsigned objcDeclQualifier : 6;
374
375  /// Default argument, if any.  [C++ Only]
376  Expr *DefaultArg;
377protected:
378  ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation L,
379              IdentifierInfo *Id, QualType T, StorageClass S,
380              Expr *DefArg)
381    : VarDecl(DK, DC, L, Id, T, S),
382      objcDeclQualifier(OBJC_TQ_None), DefaultArg(DefArg) {}
383
384public:
385  static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
386                             SourceLocation L,IdentifierInfo *Id,
387                             QualType T, StorageClass S, Expr *DefArg);
388
389  ObjCDeclQualifier getObjCDeclQualifier() const {
390    return ObjCDeclQualifier(objcDeclQualifier);
391  }
392  void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
393    objcDeclQualifier = QTVal;
394  }
395
396  const Expr *getDefaultArg() const { return DefaultArg; }
397  Expr *getDefaultArg() { return DefaultArg; }
398  void setDefaultArg(Expr *defarg) { DefaultArg = defarg; }
399
400  /// hasUnparsedDefaultArg - Determines whether this parameter has a
401  /// default argument that has not yet been parsed. This will occur
402  /// during the processing of a C++ class whose member functions have
403  /// default arguments, e.g.,
404  /// @code
405  ///   class X {
406  ///   public:
407  ///     void f(int x = 17); // x has an unparsed default argument now
408  ///   }; // x has a regular default argument now
409  /// @endcode
410  bool hasUnparsedDefaultArg() const {
411    return DefaultArg == reinterpret_cast<Expr *>(-1);
412  }
413
414  /// setUnparsedDefaultArg - Specify that this parameter has an
415  /// unparsed default argument. The argument will be replaced with a
416  /// real default argument via setDefaultArg when the class
417  /// definition enclosing the function declaration that owns this
418  /// default argument is completed.
419  void setUnparsedDefaultArg() { DefaultArg = reinterpret_cast<Expr *>(-1); }
420
421  QualType getOriginalType() const;
422
423  /// setOwningFunction - Sets the function declaration that owns this
424  /// ParmVarDecl. Since ParmVarDecls are often created before the
425  /// FunctionDecls that own them, this routine is required to update
426  /// the DeclContext appropriately.
427  void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
428
429  // Implement isa/cast/dyncast/etc.
430  static bool classof(const Decl *D) {
431    return (D->getKind() == ParmVar ||
432            D->getKind() == OriginalParmVar);
433  }
434  static bool classof(const ParmVarDecl *D) { return true; }
435
436protected:
437  /// EmitImpl - Serialize this ParmVarDecl. Called by Decl::Emit.
438  virtual void EmitImpl(llvm::Serializer& S) const;
439
440  /// CreateImpl - Deserialize a ParmVarDecl.  Called by Decl::Create.
441  static ParmVarDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
442
443  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
444};
445
446/// OriginalParmVarDecl - Represent a parameter to a function, when
447/// the type of the parameter has been promoted. This node represents the
448/// parameter to the function with its original type.
449///
450class OriginalParmVarDecl : public ParmVarDecl {
451  friend class ParmVarDecl;
452protected:
453  QualType OriginalType;
454private:
455  OriginalParmVarDecl(DeclContext *DC, SourceLocation L,
456                              IdentifierInfo *Id, QualType T,
457                              QualType OT, StorageClass S,
458                              Expr *DefArg)
459  : ParmVarDecl(OriginalParmVar, DC, L, Id, T, S, DefArg), OriginalType(OT) {}
460public:
461    static OriginalParmVarDecl *Create(ASTContext &C, DeclContext *DC,
462                               SourceLocation L,IdentifierInfo *Id,
463                               QualType T, QualType OT,
464                               StorageClass S, Expr *DefArg);
465
466  // Implement isa/cast/dyncast/etc.
467  static bool classof(const Decl *D) { return D->getKind() == OriginalParmVar; }
468  static bool classof(const OriginalParmVarDecl *D) { return true; }
469
470protected:
471  /// EmitImpl - Serialize this OriginalParmVarDecl.
472  /// Called by Decl::Emit.
473  virtual void EmitImpl(llvm::Serializer& S) const;
474
475  /// CreateImpl - Deserialize a OriginalParmVarDecl.
476  /// Called by Decl::Create.
477  static OriginalParmVarDecl* CreateImpl(llvm::Deserializer& D,
478                                                 ASTContext& C);
479
480  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
481};
482
483/// FunctionDecl - An instance of this class is created to represent a
484/// function declaration or definition.
485///
486/// Since a given function can be declared several times in a program,
487/// there may be several FunctionDecls that correspond to that
488/// function. Only one of those FunctionDecls will be found when
489/// traversing the list of declarations in the context of the
490/// FunctionDecl (e.g., the translation unit); this FunctionDecl
491/// contains all of the information known about the function. Other,
492/// previous declarations of the function are available via the
493/// getPreviousDeclaration() chain.
494class FunctionDecl : public ValueDecl, public DeclContext {
495public:
496  enum StorageClass {
497    None, Extern, Static, PrivateExtern
498  };
499private:
500  /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
501  /// parameters of this function.  This is null if a prototype or if there are
502  /// no formals.  TODO: we could allocate this space immediately after the
503  /// FunctionDecl object to save an allocation like FunctionType does.
504  ParmVarDecl **ParamInfo;
505
506  Stmt *Body;  // Null if a prototype.
507
508  /// PreviousDeclaration - A link to the previous declaration of this
509  /// same function, NULL if this is the first declaration. For
510  /// example, in the following code, the PreviousDeclaration can be
511  /// traversed several times to see all three declarations of the
512  /// function "f", the last of which is also a definition.
513  ///
514  ///   int f(int x, int y = 1);
515  ///   int f(int x = 0, int y);
516  ///   int f(int x, int y) { return x + y; }
517  FunctionDecl *PreviousDeclaration;
518
519  // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
520  unsigned SClass : 2;
521  bool IsInline : 1;
522  bool IsVirtual : 1;
523  bool IsPure : 1;
524
525  // Move to DeclGroup when it is implemented.
526  SourceLocation TypeSpecStartLoc;
527protected:
528  FunctionDecl(Kind DK, DeclContext *DC, SourceLocation L,
529               DeclarationName N, QualType T,
530               StorageClass S, bool isInline,
531               SourceLocation TSSL = SourceLocation())
532    : ValueDecl(DK, DC, L, N, T),
533      DeclContext(DK),
534      ParamInfo(0), Body(0), PreviousDeclaration(0),
535      SClass(S), IsInline(isInline), IsVirtual(false), IsPure(false),
536      TypeSpecStartLoc(TSSL) {}
537
538  virtual ~FunctionDecl() {}
539  virtual void Destroy(ASTContext& C);
540
541public:
542  static FunctionDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
543                              DeclarationName N, QualType T,
544                              StorageClass S = None, bool isInline = false,
545                              SourceLocation TSStartLoc = SourceLocation());
546
547  SourceLocation getTypeSpecStartLoc() const { return TypeSpecStartLoc; }
548
549  /// getBody - Retrieve the body (definition) of the function. The
550  /// function body might be in any of the (re-)declarations of this
551  /// function. The variant that accepts a FunctionDecl pointer will
552  /// set that function declaration to the actual declaration
553  /// containing the body (if there is one).
554  Stmt *getBody(const FunctionDecl *&Definition) const;
555
556  virtual Stmt *getBody() const {
557    const FunctionDecl* Definition;
558    return getBody(Definition);
559  }
560
561  /// isThisDeclarationADefinition - Returns whether this specific
562  /// declaration of the function is also a definition. This does not
563  /// determine whether the function has been defined (e.g., in a
564  /// previous definition); for that information, use getBody.
565  bool isThisDeclarationADefinition() const { return Body != 0; }
566
567  void setBody(Stmt *B) { Body = B; }
568
569  /// Whether this function is virtual, either by explicit marking, or by
570  /// overriding a virtual function. Only valid on C++ member functions.
571  bool isVirtual() { return IsVirtual; }
572  void setVirtual() { IsVirtual = true; }
573
574  /// Whether this virtual function is pure, i.e. makes the containing class
575  /// abstract.
576  bool isPure() { return IsPure; }
577  void setPure() { IsPure = true; }
578
579  /// getPreviousDeclaration - Return the previous declaration of this
580  /// function.
581  const FunctionDecl *getPreviousDeclaration() const {
582    return PreviousDeclaration;
583  }
584
585  void setPreviousDeclaration(FunctionDecl * PrevDecl) {
586    PreviousDeclaration = PrevDecl;
587  }
588
589  // Iterator access to formal parameters.
590  unsigned param_size() const { return getNumParams(); }
591  typedef ParmVarDecl **param_iterator;
592  typedef ParmVarDecl * const *param_const_iterator;
593
594  param_iterator param_begin() { return ParamInfo; }
595  param_iterator param_end()   { return ParamInfo+param_size(); }
596
597  param_const_iterator param_begin() const { return ParamInfo; }
598  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
599
600  unsigned getNumParams() const;
601  const ParmVarDecl *getParamDecl(unsigned i) const {
602    assert(i < getNumParams() && "Illegal param #");
603    return ParamInfo[i];
604  }
605  ParmVarDecl *getParamDecl(unsigned i) {
606    assert(i < getNumParams() && "Illegal param #");
607    return ParamInfo[i];
608  }
609  void setParams(ASTContext& C, ParmVarDecl **NewParamInfo, unsigned NumParams);
610
611  /// getMinRequiredArguments - Returns the minimum number of arguments
612  /// needed to call this function. This may be fewer than the number of
613  /// function parameters, if some of the parameters have default
614  /// arguments (in C++).
615  unsigned getMinRequiredArguments() const;
616
617  QualType getResultType() const {
618    return getType()->getAsFunctionType()->getResultType();
619  }
620  StorageClass getStorageClass() const { return StorageClass(SClass); }
621  bool isInline() const { return IsInline; }
622
623  /// isOverloadedOperator - Whether this function declaration
624  /// represents an C++ overloaded operator, e.g., "operator+".
625  bool isOverloadedOperator() const {
626    return getOverloadedOperator() != OO_None;
627  };
628
629  OverloadedOperatorKind getOverloadedOperator() const;
630
631  // Implement isa/cast/dyncast/etc.
632  static bool classof(const Decl *D) {
633    return D->getKind() >= FunctionFirst && D->getKind() <= FunctionLast;
634  }
635  static bool classof(const FunctionDecl *D) { return true; }
636  static DeclContext *castToDeclContext(const FunctionDecl *D) {
637    return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
638  }
639  static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
640    return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
641  }
642
643protected:
644  /// EmitImpl - Serialize this FunctionDecl.  Called by Decl::Emit.
645  virtual void EmitImpl(llvm::Serializer& S) const;
646
647  /// CreateImpl - Deserialize a FunctionDecl.  Called by Decl::Create.
648  static FunctionDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
649
650  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
651  friend class CXXRecordDecl;
652};
653
654
655/// FieldDecl - An instance of this class is created by Sema::ActOnField to
656/// represent a member of a struct/union/class.
657class FieldDecl : public NamedDecl {
658  bool Mutable : 1;
659  QualType DeclType;
660  Expr *BitWidth;
661protected:
662  FieldDecl(Kind DK, DeclContext *DC, SourceLocation L,
663            IdentifierInfo *Id, QualType T, Expr *BW, bool Mutable)
664    : NamedDecl(DK, DC, L, Id), Mutable(Mutable), DeclType(T),
665      BitWidth(BW)
666      { }
667
668public:
669  static FieldDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
670                           IdentifierInfo *Id, QualType T, Expr *BW,
671                           bool Mutable);
672
673  QualType getType() const { return DeclType; }
674
675  /// isMutable - Determines whether this field is mutable (C++ only).
676  bool isMutable() const { return Mutable; }
677
678  /// isBitfield - Determines whether this field is a bitfield.
679  bool isBitField() const { return BitWidth != NULL; }
680
681  /// @brief Determines whether this is an unnamed bitfield.
682  bool isUnnamedBitfield() const { return BitWidth != NULL && !getDeclName(); }
683
684  /// isAnonymousStructOrUnion - Determines whether this field is a
685  /// representative for an anonymous struct or union. Such fields are
686  /// unnamed and are implicitly generated by the implementation to
687  /// store the data for the anonymous union or struct.
688  bool isAnonymousStructOrUnion() const;
689
690  Expr *getBitWidth() const { return BitWidth; }
691  // Implement isa/cast/dyncast/etc.
692  static bool classof(const Decl *D) {
693    return D->getKind() >= FieldFirst && D->getKind() <= FieldLast;
694  }
695  static bool classof(const FieldDecl *D) { return true; }
696
697protected:
698  /// EmitImpl - Serialize this FieldDecl.  Called by Decl::Emit.
699  virtual void EmitImpl(llvm::Serializer& S) const;
700
701  /// CreateImpl - Deserialize a FieldDecl.  Called by Decl::Create.
702  static FieldDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
703
704  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
705};
706
707/// EnumConstantDecl - An instance of this object exists for each enum constant
708/// that is defined.  For example, in "enum X {a,b}", each of a/b are
709/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
710/// TagType for the X EnumDecl.
711class EnumConstantDecl : public ValueDecl {
712  Stmt *Init; // an integer constant expression
713  llvm::APSInt Val; // The value.
714protected:
715  EnumConstantDecl(DeclContext *DC, SourceLocation L,
716                   IdentifierInfo *Id, QualType T, Expr *E,
717                   const llvm::APSInt &V)
718    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
719
720  virtual ~EnumConstantDecl() {}
721public:
722
723  static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
724                                  SourceLocation L, IdentifierInfo *Id,
725                                  QualType T, Expr *E,
726                                  const llvm::APSInt &V);
727
728  virtual void Destroy(ASTContext& C);
729
730  const Expr *getInitExpr() const { return (const Expr*) Init; }
731  Expr *getInitExpr() { return (Expr*) Init; }
732  const llvm::APSInt &getInitVal() const { return Val; }
733
734  void setInitExpr(Expr *E) { Init = (Stmt*) E; }
735  void setInitVal(const llvm::APSInt &V) { Val = V; }
736
737  // Implement isa/cast/dyncast/etc.
738  static bool classof(const Decl *D) { return D->getKind() == EnumConstant; }
739  static bool classof(const EnumConstantDecl *D) { return true; }
740
741  friend class StmtIteratorBase;
742
743protected:
744  /// EmitImpl - Serialize this EnumConstantDecl.  Called by Decl::Emit.
745  virtual void EmitImpl(llvm::Serializer& S) const;
746
747  /// CreateImpl - Deserialize a EnumConstantDecl.  Called by Decl::Create.
748  static EnumConstantDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
749
750  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
751};
752
753
754/// TypeDecl - Represents a declaration of a type.
755///
756class TypeDecl : public NamedDecl {
757  /// TypeForDecl - This indicates the Type object that represents this
758  /// TypeDecl.  It is a cache maintained by ASTContext::getTypedefType,
759  /// ASTContext::getTagDeclType, and ASTContext::getTemplateTypeParmType.
760  Type *TypeForDecl;
761  friend class ASTContext;
762  friend class DeclContext;
763  friend class TagDecl;
764
765protected:
766  TypeDecl(Kind DK, DeclContext *DC, SourceLocation L,
767           IdentifierInfo *Id)
768    : NamedDecl(DK, DC, L, Id), TypeForDecl(0) {}
769
770public:
771  // Implement isa/cast/dyncast/etc.
772  static bool classof(const Decl *D) {
773    return D->getKind() >= TypeFirst && D->getKind() <= TypeLast;
774  }
775  static bool classof(const TypeDecl *D) { return true; }
776};
777
778
779class TypedefDecl : public TypeDecl {
780  /// UnderlyingType - This is the type the typedef is set to.
781  QualType UnderlyingType;
782  TypedefDecl(DeclContext *DC, SourceLocation L,
783              IdentifierInfo *Id, QualType T)
784    : TypeDecl(Typedef, DC, L, Id), UnderlyingType(T) {}
785
786  virtual ~TypedefDecl() {}
787public:
788
789  static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
790                             SourceLocation L,IdentifierInfo *Id,
791                             QualType T);
792
793  QualType getUnderlyingType() const { return UnderlyingType; }
794  void setUnderlyingType(QualType newType) { UnderlyingType = newType; }
795
796  // Implement isa/cast/dyncast/etc.
797  static bool classof(const Decl *D) { return D->getKind() == Typedef; }
798  static bool classof(const TypedefDecl *D) { return true; }
799
800protected:
801  /// EmitImpl - Serialize this TypedefDecl.  Called by Decl::Emit.
802  virtual void EmitImpl(llvm::Serializer& S) const;
803
804  /// CreateImpl - Deserialize a TypedefDecl.  Called by Decl::Create.
805  static TypedefDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
806
807  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
808};
809
810
811/// TagDecl - Represents the declaration of a struct/union/class/enum.
812class TagDecl : public TypeDecl, public DeclContext {
813public:
814  enum TagKind {
815    TK_struct,
816    TK_union,
817    TK_class,
818    TK_enum
819  };
820
821private:
822  /// TagDeclKind - The TagKind enum.
823  unsigned TagDeclKind : 2;
824
825  /// IsDefinition - True if this is a definition ("struct foo {};"), false if
826  /// it is a declaration ("struct foo;").
827  bool IsDefinition : 1;
828protected:
829  TagDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L,
830          IdentifierInfo *Id)
831    : TypeDecl(DK, DC, L, Id), DeclContext(DK) {
832    assert((DK != Enum || TK == TK_enum) &&"EnumDecl not matched with TK_enum");
833    TagDeclKind = TK;
834    IsDefinition = false;
835  }
836public:
837
838  /// isDefinition - Return true if this decl has its body specified.
839  bool isDefinition() const {
840    return IsDefinition;
841  }
842
843  /// @brief Starts the definition of this tag declaration.
844  ///
845  /// This method should be invoked at the beginning of the definition
846  /// of this tag declaration. It will set the tag type into a state
847  /// where it is in the process of being defined.
848  void startDefinition();
849
850  /// @brief Completes the definition of this tag declaration.
851  void completeDefinition();
852
853  /// getDefinition - Returns the TagDecl that actually defines this
854  ///  struct/union/class/enum.  When determining whether or not a
855  ///  struct/union/class/enum is completely defined, one should use this method
856  ///  as opposed to 'isDefinition'.  'isDefinition' indicates whether or not a
857  ///  specific TagDecl is defining declaration, not whether or not the
858  ///  struct/union/class/enum type is defined.  This method returns NULL if
859  ///  there is no TagDecl that defines the struct/union/class/enum.
860  TagDecl* getDefinition(ASTContext& C) const;
861
862  const char *getKindName() const {
863    switch (getTagKind()) {
864    default: assert(0 && "Unknown TagKind!");
865    case TK_struct: return "struct";
866    case TK_union:  return "union";
867    case TK_class:  return "class";
868    case TK_enum:   return "enum";
869    }
870  }
871
872  TagKind getTagKind() const {
873    return TagKind(TagDeclKind);
874  }
875
876  bool isStruct() const { return getTagKind() == TK_struct; }
877  bool isClass()  const { return getTagKind() == TK_class; }
878  bool isUnion()  const { return getTagKind() == TK_union; }
879  bool isEnum()   const { return getTagKind() == TK_enum; }
880
881  // Implement isa/cast/dyncast/etc.
882  static bool classof(const Decl *D) {
883    return D->getKind() >= TagFirst && D->getKind() <= TagLast;
884  }
885  static bool classof(const TagDecl *D) { return true; }
886
887  static DeclContext *castToDeclContext(const TagDecl *D) {
888    return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
889  }
890  static TagDecl *castFromDeclContext(const DeclContext *DC) {
891    return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
892  }
893
894protected:
895  void setDefinition(bool V) { IsDefinition = V; }
896};
897
898/// EnumDecl - Represents an enum.  As an extension, we allow forward-declared
899/// enums.
900class EnumDecl : public TagDecl {
901  /// IntegerType - This represent the integer type that the enum corresponds
902  /// to for code generation purposes.  Note that the enumerator constants may
903  /// have a different type than this does.
904  QualType IntegerType;
905
906  EnumDecl(DeclContext *DC, SourceLocation L,
907           IdentifierInfo *Id)
908    : TagDecl(Enum, TK_enum, DC, L, Id) {
909      IntegerType = QualType();
910    }
911public:
912  static EnumDecl *Create(ASTContext &C, DeclContext *DC,
913                          SourceLocation L, IdentifierInfo *Id,
914                          EnumDecl *PrevDecl);
915
916  virtual void Destroy(ASTContext& C);
917
918  /// completeDefinition - When created, the EnumDecl corresponds to a
919  /// forward-declared enum. This method is used to mark the
920  /// declaration as being defined; it's enumerators have already been
921  /// added (via DeclContext::addDecl). NewType is the new underlying
922  /// type of the enumeration type.
923  void completeDefinition(ASTContext &C, QualType NewType);
924
925  // enumerator_iterator - Iterates through the enumerators of this
926  // enumeration.
927  typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
928
929  enumerator_iterator enumerator_begin() const {
930    return enumerator_iterator(this->decls_begin());
931  }
932
933  enumerator_iterator enumerator_end() const {
934    return enumerator_iterator(this->decls_end());
935  }
936
937  /// getIntegerType - Return the integer type this enum decl corresponds to.
938  /// This returns a null qualtype for an enum forward definition.
939  QualType getIntegerType() const { return IntegerType; }
940
941  static bool classof(const Decl *D) { return D->getKind() == Enum; }
942  static bool classof(const EnumDecl *D) { return true; }
943  static DeclContext *castToDeclContext(const EnumDecl *D) {
944    return static_cast<DeclContext *>(const_cast<EnumDecl*>(D));
945  }
946  static EnumDecl *castFromDeclContext(const DeclContext *DC) {
947    return static_cast<EnumDecl *>(const_cast<DeclContext*>(DC));
948  }
949
950protected:
951  /// EmitImpl - Serialize this EnumDecl.  Called by Decl::Emit.
952  virtual void EmitImpl(llvm::Serializer& S) const;
953
954  /// CreateImpl - Deserialize a EnumDecl.  Called by Decl::Create.
955  static EnumDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
956
957  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
958};
959
960
961/// RecordDecl - Represents a struct/union/class.  For example:
962///   struct X;                  // Forward declaration, no "body".
963///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
964/// This decl will be marked invalid if *any* members are invalid.
965///
966class RecordDecl : public TagDecl {
967  /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
968  /// array member (e.g. int X[]) or if this union contains a struct that does.
969  /// If so, this cannot be contained in arrays or other structs as a member.
970  bool HasFlexibleArrayMember : 1;
971
972  /// AnonymousStructOrUnion - Whether this is the type of an
973  /// anonymous struct or union.
974  bool AnonymousStructOrUnion : 1;
975
976protected:
977  RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
978             SourceLocation L, IdentifierInfo *Id);
979  virtual ~RecordDecl();
980
981public:
982  static RecordDecl *Create(ASTContext &C, TagKind TK, DeclContext *DC,
983                            SourceLocation L, IdentifierInfo *Id,
984                            RecordDecl* PrevDecl = 0);
985
986  virtual void Destroy(ASTContext& C);
987
988  bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
989  void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
990
991  /// isAnonymousStructOrUnion - Whether this is an anonymous struct
992  /// or union. To be an anonymous struct or union, it must have been
993  /// declared without a name and there must be no objects of this
994  /// type declared, e.g.,
995  /// @code
996  ///   union { int i; float f; };
997  /// @endcode
998  /// is an anonymous union but neither of the following are:
999  /// @code
1000  ///  union X { int i; float f; };
1001  ///  union { int i; float f; } obj;
1002  /// @endcode
1003  bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
1004  void setAnonymousStructOrUnion(bool Anon) {
1005    AnonymousStructOrUnion = Anon;
1006  }
1007
1008  /// getDefinition - Returns the RecordDecl that actually defines this
1009  ///  struct/union/class.  When determining whether or not a struct/union/class
1010  ///  is completely defined, one should use this method as opposed to
1011  ///  'isDefinition'.  'isDefinition' indicates whether or not a specific
1012  ///  RecordDecl is defining declaration, not whether or not the record
1013  ///  type is defined.  This method returns NULL if there is no RecordDecl
1014  ///  that defines the struct/union/tag.
1015  RecordDecl* getDefinition(ASTContext& C) const {
1016    return cast_or_null<RecordDecl>(TagDecl::getDefinition(C));
1017  }
1018
1019  // Iterator access to field members. The field iterator only visits
1020  // the non-static data members of this class, ignoring any static
1021  // data members, functions, constructors, destructors, etc.
1022  typedef specific_decl_iterator<FieldDecl> field_iterator;
1023
1024  field_iterator field_begin() const {
1025    return field_iterator(decls_begin());
1026  }
1027  field_iterator field_end() const {
1028    return field_iterator(decls_end());
1029  }
1030
1031  // field_empty - Whether there are any fields (non-static data
1032  // members) in this record.
1033  bool field_empty() const { return field_begin() == field_end(); }
1034
1035  /// completeDefinition - Notes that the definition of this type is
1036  /// now complete.
1037  void completeDefinition(ASTContext& C);
1038
1039  static bool classof(const Decl *D) {
1040    return D->getKind() >= RecordFirst && D->getKind() <= RecordLast;
1041  }
1042  static bool classof(const RecordDecl *D) { return true; }
1043  static DeclContext *castToDeclContext(const RecordDecl *D) {
1044    return static_cast<DeclContext *>(const_cast<RecordDecl*>(D));
1045  }
1046  static RecordDecl *castFromDeclContext(const DeclContext *DC) {
1047    return static_cast<RecordDecl *>(const_cast<DeclContext*>(DC));
1048  }
1049protected:
1050  /// EmitImpl - Serialize this RecordDecl.  Called by Decl::Emit.
1051  virtual void EmitImpl(llvm::Serializer& S) const;
1052
1053  /// CreateImpl - Deserialize a RecordDecl.  Called by Decl::Create.
1054  static RecordDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1055
1056  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
1057};
1058
1059class FileScopeAsmDecl : public Decl {
1060  StringLiteral *AsmString;
1061  FileScopeAsmDecl(DeclContext *DC, SourceLocation L, StringLiteral *asmstring)
1062    : Decl(FileScopeAsm, DC, L), AsmString(asmstring) {}
1063public:
1064  static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
1065                                  SourceLocation L, StringLiteral *Str);
1066
1067  const StringLiteral *getAsmString() const { return AsmString; }
1068  StringLiteral *getAsmString() { return AsmString; }
1069  static bool classof(const Decl *D) {
1070    return D->getKind() == FileScopeAsm;
1071  }
1072  static bool classof(const FileScopeAsmDecl *D) { return true; }
1073protected:
1074  /// EmitImpl - Serialize this FileScopeAsmDecl. Called by Decl::Emit.
1075  virtual void EmitImpl(llvm::Serializer& S) const;
1076
1077  /// CreateImpl - Deserialize a FileScopeAsmDecl.  Called by Decl::Create.
1078  static FileScopeAsmDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1079
1080  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
1081};
1082
1083/// BlockDecl - This represents a block literal declaration, which is like an
1084/// unnamed FunctionDecl.  For example:
1085/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
1086///
1087class BlockDecl : public Decl, public DeclContext {
1088  llvm::SmallVector<ParmVarDecl*, 8> Args;
1089  Stmt *Body;
1090
1091protected:
1092  BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
1093    : Decl(Block, DC, CaretLoc), DeclContext(Block), Body(0) {}
1094
1095  virtual ~BlockDecl();
1096  virtual void Destroy(ASTContext& C);
1097
1098public:
1099  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
1100
1101  SourceLocation getCaretLocation() const { return getLocation(); }
1102
1103  Stmt *getBody() const { return Body; }
1104  void setBody(Stmt *B) { Body = B; }
1105
1106  void setArgs(ParmVarDecl **args, unsigned numargs) {
1107    Args.clear();
1108    Args.insert(Args.begin(), args, args+numargs);
1109  }
1110
1111  /// arg_iterator - Iterate over the ParmVarDecl's for this block.
1112  typedef llvm::SmallVector<ParmVarDecl*, 8>::const_iterator param_iterator;
1113  bool param_empty() const { return Args.empty(); }
1114  param_iterator param_begin() const { return Args.begin(); }
1115  param_iterator param_end() const { return Args.end(); }
1116
1117  // Implement isa/cast/dyncast/etc.
1118  static bool classof(const Decl *D) { return D->getKind() == Block; }
1119  static bool classof(const BlockDecl *D) { return true; }
1120  static DeclContext *castToDeclContext(const BlockDecl *D) {
1121    return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
1122  }
1123  static BlockDecl *castFromDeclContext(const DeclContext *DC) {
1124    return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
1125  }
1126
1127protected:
1128  /// EmitImpl - Serialize this BlockDecl. Called by Decl::Emit.
1129  virtual void EmitImpl(llvm::Serializer& S) const;
1130
1131  /// CreateImpl - Deserialize a BlockDecl.  Called by Decl::Create.
1132  static BlockDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1133
1134  friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C);
1135};
1136
1137}  // end namespace clang
1138
1139#endif
1140