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