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