DeclSpec.h revision d067c07c6cbf099b25aba38bcb66f38e79d0c420
1//===--- DeclSpec.h - Parsed declaration specifiers -------------*- 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 classes used to store parsed information about
11// declaration-specifiers and declarators.
12//
13//   static const int volatile x, *y, *(*(*z)[10])(const void *x);
14//   ------------------------- -  --  ---------------------------
15//     declaration-specifiers  \  |   /
16//                            declarators
17//
18//===----------------------------------------------------------------------===//
19
20#ifndef LLVM_CLANG_SEMA_DECLSPEC_H
21#define LLVM_CLANG_SEMA_DECLSPEC_H
22
23#include "clang/Sema/AttributeList.h"
24#include "clang/Sema/Ownership.h"
25#include "clang/Lex/Token.h"
26#include "clang/Basic/OperatorKinds.h"
27#include "clang/Basic/Specifiers.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/Support/ErrorHandling.h"
30
31namespace clang {
32  class LangOptions;
33  class Diagnostic;
34  class IdentifierInfo;
35  class NestedNameSpecifier;
36  class Preprocessor;
37  class Declarator;
38  struct TemplateIdAnnotation;
39
40/// CXXScopeSpec - Represents a C++ nested-name-specifier or a global scope
41/// specifier.  These can be in 3 states:
42///   1) Not present, identified by isEmpty()
43///   2) Present, identified by isNotEmpty()
44///      2.a) Valid, idenified by isValid()
45///      2.b) Invalid, identified by isInvalid().
46///
47/// isSet() is deprecated because it mostly corresponded to "valid" but was
48/// often used as if it meant "present".
49///
50/// The actual scope is described by getScopeRep().
51class CXXScopeSpec {
52  SourceRange Range;
53  NestedNameSpecifier *ScopeRep;
54
55public:
56  CXXScopeSpec() : Range(), ScopeRep() { }
57
58  const SourceRange &getRange() const { return Range; }
59  void setRange(const SourceRange &R) { Range = R; }
60  void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
61  void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
62  SourceLocation getBeginLoc() const { return Range.getBegin(); }
63  SourceLocation getEndLoc() const { return Range.getEnd(); }
64
65  NestedNameSpecifier *getScopeRep() const { return ScopeRep; }
66  void setScopeRep(NestedNameSpecifier *S) { ScopeRep = S; }
67
68  /// No scope specifier.
69  bool isEmpty() const { return !Range.isValid(); }
70  /// A scope specifier is present, but may be valid or invalid.
71  bool isNotEmpty() const { return !isEmpty(); }
72
73  /// An error occured during parsing of the scope specifier.
74  bool isInvalid() const { return isNotEmpty() && ScopeRep == 0; }
75  /// A scope specifier is present, and it refers to a real scope.
76  bool isValid() const { return isNotEmpty() && ScopeRep != 0; }
77
78  /// Deprecated.  Some call sites intend isNotEmpty() while others intend
79  /// isValid().
80  bool isSet() const { return ScopeRep != 0; }
81
82  void clear() {
83    Range = SourceRange();
84    ScopeRep = 0;
85  }
86};
87
88/// DeclSpec - This class captures information about "declaration specifiers",
89/// which encompasses storage-class-specifiers, type-specifiers,
90/// type-qualifiers, and function-specifiers.
91class DeclSpec {
92public:
93  // storage-class-specifier
94  // Note: The order of these enumerators is important for diagnostics.
95  enum SCS {
96    SCS_unspecified = 0,
97    SCS_typedef,
98    SCS_extern,
99    SCS_static,
100    SCS_auto,
101    SCS_register,
102    SCS_private_extern,
103    SCS_mutable
104  };
105
106  // Import type specifier width enumeration and constants.
107  typedef TypeSpecifierWidth TSW;
108  static const TSW TSW_unspecified = clang::TSW_unspecified;
109  static const TSW TSW_short = clang::TSW_short;
110  static const TSW TSW_long = clang::TSW_long;
111  static const TSW TSW_longlong = clang::TSW_longlong;
112
113  enum TSC {
114    TSC_unspecified,
115    TSC_imaginary,
116    TSC_complex
117  };
118
119  // Import type specifier sign enumeration and constants.
120  typedef TypeSpecifierSign TSS;
121  static const TSS TSS_unspecified = clang::TSS_unspecified;
122  static const TSS TSS_signed = clang::TSS_signed;
123  static const TSS TSS_unsigned = clang::TSS_unsigned;
124
125  // Import type specifier type enumeration and constants.
126  typedef TypeSpecifierType TST;
127  static const TST TST_unspecified = clang::TST_unspecified;
128  static const TST TST_void = clang::TST_void;
129  static const TST TST_char = clang::TST_char;
130  static const TST TST_wchar = clang::TST_wchar;
131  static const TST TST_char16 = clang::TST_char16;
132  static const TST TST_char32 = clang::TST_char32;
133  static const TST TST_int = clang::TST_int;
134  static const TST TST_float = clang::TST_float;
135  static const TST TST_double = clang::TST_double;
136  static const TST TST_bool = clang::TST_bool;
137  static const TST TST_decimal32 = clang::TST_decimal32;
138  static const TST TST_decimal64 = clang::TST_decimal64;
139  static const TST TST_decimal128 = clang::TST_decimal128;
140  static const TST TST_enum = clang::TST_enum;
141  static const TST TST_union = clang::TST_union;
142  static const TST TST_struct = clang::TST_struct;
143  static const TST TST_class = clang::TST_class;
144  static const TST TST_typename = clang::TST_typename;
145  static const TST TST_typeofType = clang::TST_typeofType;
146  static const TST TST_typeofExpr = clang::TST_typeofExpr;
147  static const TST TST_decltype = clang::TST_decltype;
148  static const TST TST_auto = clang::TST_auto;
149  static const TST TST_error = clang::TST_error;
150
151  // type-qualifiers
152  enum TQ {   // NOTE: These flags must be kept in sync with Qualifiers::TQ.
153    TQ_unspecified = 0,
154    TQ_const       = 1,
155    TQ_restrict    = 2,
156    TQ_volatile    = 4
157  };
158
159  /// ParsedSpecifiers - Flags to query which specifiers were applied.  This is
160  /// returned by getParsedSpecifiers.
161  enum ParsedSpecifiers {
162    PQ_None                  = 0,
163    PQ_StorageClassSpecifier = 1,
164    PQ_TypeSpecifier         = 2,
165    PQ_TypeQualifier         = 4,
166    PQ_FunctionSpecifier     = 8
167  };
168
169private:
170
171  // storage-class-specifier
172  /*SCS*/unsigned StorageClassSpec : 3;
173  unsigned SCS_thread_specified : 1;
174  unsigned SCS_extern_in_linkage_spec : 1;
175
176  // type-specifier
177  /*TSW*/unsigned TypeSpecWidth : 2;
178  /*TSC*/unsigned TypeSpecComplex : 2;
179  /*TSS*/unsigned TypeSpecSign : 2;
180  /*TST*/unsigned TypeSpecType : 5;
181  unsigned TypeAltiVecVector : 1;
182  unsigned TypeAltiVecPixel : 1;
183  unsigned TypeAltiVecBool : 1;
184  unsigned TypeSpecOwned : 1;
185
186  // type-qualifiers
187  unsigned TypeQualifiers : 3;  // Bitwise OR of TQ.
188
189  // function-specifier
190  unsigned FS_inline_specified : 1;
191  unsigned FS_virtual_specified : 1;
192  unsigned FS_explicit_specified : 1;
193
194  // friend-specifier
195  unsigned Friend_specified : 1;
196
197  // constexpr-specifier
198  unsigned Constexpr_specified : 1;
199
200  /*SCS*/unsigned StorageClassSpecAsWritten : 3;
201
202  union {
203    UnionParsedType TypeRep;
204    Decl *DeclRep;
205    Expr *ExprRep;
206  };
207
208  // attributes.
209  ParsedAttributes Attrs;
210
211  // Scope specifier for the type spec, if applicable.
212  CXXScopeSpec TypeScope;
213
214  // List of protocol qualifiers for objective-c classes.  Used for
215  // protocol-qualified interfaces "NString<foo>" and protocol-qualified id
216  // "id<foo>".
217  Decl * const *ProtocolQualifiers;
218  unsigned NumProtocolQualifiers;
219  SourceLocation ProtocolLAngleLoc;
220  SourceLocation *ProtocolLocs;
221
222  // SourceLocation info.  These are null if the item wasn't specified or if
223  // the setting was synthesized.
224  SourceRange Range;
225
226  SourceLocation StorageClassSpecLoc, SCS_threadLoc;
227  SourceLocation TSWLoc, TSCLoc, TSSLoc, TSTLoc, AltiVecLoc;
228  SourceRange TypeofParensRange;
229  SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc;
230  SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc;
231  SourceLocation FriendLoc, ConstexprLoc;
232
233  WrittenBuiltinSpecs writtenBS;
234  void SaveWrittenBuiltinSpecs();
235  void SaveStorageSpecifierAsWritten();
236
237  static bool isTypeRep(TST T) {
238    return (T == TST_typename || T == TST_typeofType);
239  }
240  static bool isExprRep(TST T) {
241    return (T == TST_typeofExpr || T == TST_decltype);
242  }
243  static bool isDeclRep(TST T) {
244    return (T == TST_enum || T == TST_struct ||
245            T == TST_union || T == TST_class);
246  }
247
248  DeclSpec(const DeclSpec&);       // DO NOT IMPLEMENT
249  void operator=(const DeclSpec&); // DO NOT IMPLEMENT
250public:
251
252  DeclSpec()
253    : StorageClassSpec(SCS_unspecified),
254      SCS_thread_specified(false),
255      SCS_extern_in_linkage_spec(false),
256      TypeSpecWidth(TSW_unspecified),
257      TypeSpecComplex(TSC_unspecified),
258      TypeSpecSign(TSS_unspecified),
259      TypeSpecType(TST_unspecified),
260      TypeAltiVecVector(false),
261      TypeAltiVecPixel(false),
262      TypeAltiVecBool(false),
263      TypeSpecOwned(false),
264      TypeQualifiers(TSS_unspecified),
265      FS_inline_specified(false),
266      FS_virtual_specified(false),
267      FS_explicit_specified(false),
268      Friend_specified(false),
269      Constexpr_specified(false),
270      StorageClassSpecAsWritten(SCS_unspecified),
271      ProtocolQualifiers(0),
272      NumProtocolQualifiers(0),
273      ProtocolLocs(0),
274      writtenBS() {
275  }
276  ~DeclSpec() {
277    delete [] ProtocolQualifiers;
278    delete [] ProtocolLocs;
279  }
280  // storage-class-specifier
281  SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
282  bool isThreadSpecified() const { return SCS_thread_specified; }
283  bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
284  void setExternInLinkageSpec(bool Value) {
285    SCS_extern_in_linkage_spec = Value;
286  }
287
288  SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
289  SourceLocation getThreadSpecLoc() const { return SCS_threadLoc; }
290
291  void ClearStorageClassSpecs() {
292    StorageClassSpec     = DeclSpec::SCS_unspecified;
293    SCS_thread_specified = false;
294    SCS_extern_in_linkage_spec = false;
295    StorageClassSpecLoc  = SourceLocation();
296    SCS_threadLoc        = SourceLocation();
297  }
298
299  // type-specifier
300  TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
301  TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
302  TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
303  TST getTypeSpecType() const { return (TST)TypeSpecType; }
304  bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
305  bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
306  bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
307  bool isTypeSpecOwned() const { return TypeSpecOwned; }
308  ParsedType getRepAsType() const {
309    assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
310    return TypeRep;
311  }
312  Decl *getRepAsDecl() const {
313    assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
314    return DeclRep;
315  }
316  Expr *getRepAsExpr() const {
317    assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
318    return ExprRep;
319  }
320  CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
321  const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
322
323  const SourceRange &getSourceRange() const { return Range; }
324  SourceLocation getTypeSpecWidthLoc() const { return TSWLoc; }
325  SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
326  SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
327  SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
328  SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
329
330  SourceRange getTypeofParensRange() const { return TypeofParensRange; }
331  void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
332
333  /// getSpecifierName - Turn a type-specifier-type into a string like "_Bool"
334  /// or "union".
335  static const char *getSpecifierName(DeclSpec::TST T);
336  static const char *getSpecifierName(DeclSpec::TQ Q);
337  static const char *getSpecifierName(DeclSpec::TSS S);
338  static const char *getSpecifierName(DeclSpec::TSC C);
339  static const char *getSpecifierName(DeclSpec::TSW W);
340  static const char *getSpecifierName(DeclSpec::SCS S);
341
342  // type-qualifiers
343
344  /// getTypeQualifiers - Return a set of TQs.
345  unsigned getTypeQualifiers() const { return TypeQualifiers; }
346  SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
347  SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
348  SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
349
350  // function-specifier
351  bool isInlineSpecified() const { return FS_inline_specified; }
352  SourceLocation getInlineSpecLoc() const { return FS_inlineLoc; }
353
354  bool isVirtualSpecified() const { return FS_virtual_specified; }
355  SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
356
357  bool isExplicitSpecified() const { return FS_explicit_specified; }
358  SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
359
360  void ClearFunctionSpecs() {
361    FS_inline_specified = false;
362    FS_inlineLoc = SourceLocation();
363    FS_virtual_specified = false;
364    FS_virtualLoc = SourceLocation();
365    FS_explicit_specified = false;
366    FS_explicitLoc = SourceLocation();
367  }
368
369  /// hasTypeSpecifier - Return true if any type-specifier has been found.
370  bool hasTypeSpecifier() const {
371    return getTypeSpecType() != DeclSpec::TST_unspecified ||
372           getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
373           getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
374           getTypeSpecSign() != DeclSpec::TSS_unspecified;
375  }
376
377  /// getParsedSpecifiers - Return a bitmask of which flavors of specifiers this
378  /// DeclSpec includes.
379  ///
380  unsigned getParsedSpecifiers() const;
381
382  SCS getStorageClassSpecAsWritten() const {
383    return (SCS)StorageClassSpecAsWritten;
384  }
385
386  /// isEmpty - Return true if this declaration specifier is completely empty:
387  /// no tokens were parsed in the production of it.
388  bool isEmpty() const {
389    return getParsedSpecifiers() == DeclSpec::PQ_None;
390  }
391
392  void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
393  void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
394
395  /// These methods set the specified attribute of the DeclSpec and
396  /// return false if there was no error.  If an error occurs (for
397  /// example, if we tried to set "auto" on a spec with "extern"
398  /// already set), they return true and set PrevSpec and DiagID
399  /// such that
400  ///   Diag(Loc, DiagID) << PrevSpec;
401  /// will yield a useful result.
402  ///
403  /// TODO: use a more general approach that still allows these
404  /// diagnostics to be ignored when desired.
405  bool SetStorageClassSpec(SCS S, SourceLocation Loc, const char *&PrevSpec,
406                           unsigned &DiagID, const LangOptions &Lang);
407  bool SetStorageClassSpecThread(SourceLocation Loc, const char *&PrevSpec,
408                                 unsigned &DiagID);
409  bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
410                        unsigned &DiagID);
411  bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
412                          unsigned &DiagID);
413  bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
414                       unsigned &DiagID);
415  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
416                       unsigned &DiagID);
417  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
418                       unsigned &DiagID, ParsedType Rep);
419  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
420                       unsigned &DiagID, Decl *Rep, bool Owned);
421  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
422                       unsigned &DiagID, Expr *Rep);
423  bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
424                       const char *&PrevSpec, unsigned &DiagID);
425  bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
426                       const char *&PrevSpec, unsigned &DiagID);
427  bool SetTypeSpecError();
428  void UpdateDeclRep(Decl *Rep) {
429    assert(isDeclRep((TST) TypeSpecType));
430    DeclRep = Rep;
431  }
432  void UpdateTypeRep(ParsedType Rep) {
433    assert(isTypeRep((TST) TypeSpecType));
434    TypeRep = Rep;
435  }
436  void UpdateExprRep(Expr *Rep) {
437    assert(isExprRep((TST) TypeSpecType));
438    ExprRep = Rep;
439  }
440
441  bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
442                   unsigned &DiagID, const LangOptions &Lang);
443
444  bool SetFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
445                             unsigned &DiagID);
446  bool SetFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
447                              unsigned &DiagID);
448  bool SetFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
449                               unsigned &DiagID);
450
451  bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
452                     unsigned &DiagID);
453
454  bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
455                        unsigned &DiagID);
456
457  bool isFriendSpecified() const { return Friend_specified; }
458  SourceLocation getFriendSpecLoc() const { return FriendLoc; }
459
460  bool isConstexprSpecified() const { return Constexpr_specified; }
461  SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
462
463  /// AddAttributes - contatenates two attribute lists.
464  /// The GCC attribute syntax allows for the following:
465  ///
466  /// short __attribute__(( unused, deprecated ))
467  /// int __attribute__(( may_alias, aligned(16) )) var;
468  ///
469  /// This declares 4 attributes using 2 lists. The following syntax is
470  /// also allowed and equivalent to the previous declaration.
471  ///
472  /// short __attribute__((unused)) __attribute__((deprecated))
473  /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
474  ///
475  void addAttributes(AttributeList *AL) {
476    Attrs.append(AL);
477  }
478  void aetAttributes(AttributeList *AL) {
479    Attrs.set(AL);
480  }
481
482  bool hasAttributes() const { return !Attrs.empty(); }
483
484  ParsedAttributes &getAttributes() { return Attrs; }
485  const ParsedAttributes &getAttributes() const { return Attrs; }
486
487  /// TakeAttributes - Return the current attribute list and remove them from
488  /// the DeclSpec so that it doesn't own them.
489  ParsedAttributes takeAttributes() {
490    ParsedAttributes saved = Attrs;
491    Attrs.clear();
492    return saved;
493  }
494
495  void takeAttributesFrom(ParsedAttributes &attrs) {
496    Attrs.append(attrs.getList());
497    attrs.clear();
498  }
499
500  typedef Decl * const *ProtocolQualifierListTy;
501  ProtocolQualifierListTy getProtocolQualifiers() const {
502    return ProtocolQualifiers;
503  }
504  SourceLocation *getProtocolLocs() const { return ProtocolLocs; }
505  unsigned getNumProtocolQualifiers() const {
506    return NumProtocolQualifiers;
507  }
508  SourceLocation getProtocolLAngleLoc() const { return ProtocolLAngleLoc; }
509  void setProtocolQualifiers(Decl * const *Protos, unsigned NP,
510                             SourceLocation *ProtoLocs,
511                             SourceLocation LAngleLoc);
512
513  /// Finish - This does final analysis of the declspec, issuing diagnostics for
514  /// things like "_Imaginary" (lacking an FP type).  After calling this method,
515  /// DeclSpec is guaranteed self-consistent, even if an error occurred.
516  void Finish(Diagnostic &D, Preprocessor &PP);
517
518  const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
519    return writtenBS;
520  }
521
522  /// isMissingDeclaratorOk - This checks if this DeclSpec can stand alone,
523  /// without a Declarator. Only tag declspecs can stand alone.
524  bool isMissingDeclaratorOk();
525};
526
527/// ObjCDeclSpec - This class captures information about
528/// "declaration specifiers" specific to objective-c
529class ObjCDeclSpec {
530public:
531  /// ObjCDeclQualifier - Qualifier used on types in method declarations
532  enum ObjCDeclQualifier {
533    DQ_None = 0x0,
534    DQ_In = 0x1,
535    DQ_Inout = 0x2,
536    DQ_Out = 0x4,
537    DQ_Bycopy = 0x8,
538    DQ_Byref = 0x10,
539    DQ_Oneway = 0x20
540  };
541
542  /// PropertyAttributeKind - list of property attributes.
543  enum ObjCPropertyAttributeKind { DQ_PR_noattr = 0x0,
544    DQ_PR_readonly = 0x01,
545    DQ_PR_getter = 0x02,
546    DQ_PR_assign = 0x04,
547    DQ_PR_readwrite = 0x08,
548    DQ_PR_retain = 0x10,
549    DQ_PR_copy = 0x20,
550    DQ_PR_nonatomic = 0x40,
551    DQ_PR_setter = 0x80,
552    DQ_PR_atomic = 0x100
553  };
554
555
556  ObjCDeclSpec()
557    : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
558      GetterName(0), SetterName(0) { }
559  ObjCDeclQualifier getObjCDeclQualifier() const { return objcDeclQualifier; }
560  void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
561    objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
562  }
563
564  ObjCPropertyAttributeKind getPropertyAttributes() const {
565    return ObjCPropertyAttributeKind(PropertyAttributes);
566  }
567  void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
568    PropertyAttributes =
569      (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
570  }
571
572  const IdentifierInfo *getGetterName() const { return GetterName; }
573  IdentifierInfo *getGetterName() { return GetterName; }
574  void setGetterName(IdentifierInfo *name) { GetterName = name; }
575
576  const IdentifierInfo *getSetterName() const { return SetterName; }
577  IdentifierInfo *getSetterName() { return SetterName; }
578  void setSetterName(IdentifierInfo *name) { SetterName = name; }
579private:
580  // FIXME: These two are unrelated and mutially exclusive. So perhaps
581  // we can put them in a union to reflect their mutual exclusiveness
582  // (space saving is negligible).
583  ObjCDeclQualifier objcDeclQualifier : 6;
584
585  // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
586  unsigned PropertyAttributes : 9;
587  IdentifierInfo *GetterName;    // getter name of NULL if no getter
588  IdentifierInfo *SetterName;    // setter name of NULL if no setter
589};
590
591/// \brief Represents a C++ unqualified-id that has been parsed.
592class UnqualifiedId {
593private:
594  const UnqualifiedId &operator=(const UnqualifiedId &); // DO NOT IMPLEMENT
595
596public:
597  /// \brief Describes the kind of unqualified-id parsed.
598  enum IdKind {
599    /// \brief An identifier.
600    IK_Identifier,
601    /// \brief An overloaded operator name, e.g., operator+.
602    IK_OperatorFunctionId,
603    /// \brief A conversion function name, e.g., operator int.
604    IK_ConversionFunctionId,
605    /// \brief A user-defined literal name, e.g., operator "" _i.
606    IK_LiteralOperatorId,
607    /// \brief A constructor name.
608    IK_ConstructorName,
609    /// \brief A constructor named via a template-id.
610    IK_ConstructorTemplateId,
611    /// \brief A destructor name.
612    IK_DestructorName,
613    /// \brief A template-id, e.g., f<int>.
614    IK_TemplateId
615  } Kind;
616
617  /// \brief Anonymous union that holds extra data associated with the
618  /// parsed unqualified-id.
619  union {
620    /// \brief When Kind == IK_Identifier, the parsed identifier, or when Kind
621    /// == IK_UserLiteralId, the identifier suffix.
622    IdentifierInfo *Identifier;
623
624    /// \brief When Kind == IK_OperatorFunctionId, the overloaded operator
625    /// that we parsed.
626    struct {
627      /// \brief The kind of overloaded operator.
628      OverloadedOperatorKind Operator;
629
630      /// \brief The source locations of the individual tokens that name
631      /// the operator, e.g., the "new", "[", and "]" tokens in
632      /// operator new [].
633      ///
634      /// Different operators have different numbers of tokens in their name,
635      /// up to three. Any remaining source locations in this array will be
636      /// set to an invalid value for operators with fewer than three tokens.
637      unsigned SymbolLocations[3];
638    } OperatorFunctionId;
639
640    /// \brief When Kind == IK_ConversionFunctionId, the type that the
641    /// conversion function names.
642    UnionParsedType ConversionFunctionId;
643
644    /// \brief When Kind == IK_ConstructorName, the class-name of the type
645    /// whose constructor is being referenced.
646    UnionParsedType ConstructorName;
647
648    /// \brief When Kind == IK_DestructorName, the type referred to by the
649    /// class-name.
650    UnionParsedType DestructorName;
651
652    /// \brief When Kind == IK_TemplateId or IK_ConstructorTemplateId,
653    /// the template-id annotation that contains the template name and
654    /// template arguments.
655    TemplateIdAnnotation *TemplateId;
656  };
657
658  /// \brief The location of the first token that describes this unqualified-id,
659  /// which will be the location of the identifier, "operator" keyword,
660  /// tilde (for a destructor), or the template name of a template-id.
661  SourceLocation StartLocation;
662
663  /// \brief The location of the last token that describes this unqualified-id.
664  SourceLocation EndLocation;
665
666  UnqualifiedId() : Kind(IK_Identifier), Identifier(0) { }
667
668  /// \brief Do not use this copy constructor. It is temporary, and only
669  /// exists because we are holding FieldDeclarators in a SmallVector when we
670  /// don't actually need them.
671  ///
672  /// FIXME: Kill this copy constructor.
673  UnqualifiedId(const UnqualifiedId &Other)
674    : Kind(IK_Identifier), Identifier(Other.Identifier),
675      StartLocation(Other.StartLocation), EndLocation(Other.EndLocation) {
676    assert(Other.Kind == IK_Identifier && "Cannot copy non-identifiers");
677  }
678
679  /// \brief Destroy this unqualified-id.
680  ~UnqualifiedId() { clear(); }
681
682  /// \brief Clear out this unqualified-id, setting it to default (invalid)
683  /// state.
684  void clear();
685
686  /// \brief Determine whether this unqualified-id refers to a valid name.
687  bool isValid() const { return StartLocation.isValid(); }
688
689  /// \brief Determine whether this unqualified-id refers to an invalid name.
690  bool isInvalid() const { return !isValid(); }
691
692  /// \brief Determine what kind of name we have.
693  IdKind getKind() const { return Kind; }
694
695  /// \brief Specify that this unqualified-id was parsed as an identifier.
696  ///
697  /// \param Id the parsed identifier.
698  /// \param IdLoc the location of the parsed identifier.
699  void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
700    Kind = IK_Identifier;
701    Identifier = const_cast<IdentifierInfo *>(Id);
702    StartLocation = EndLocation = IdLoc;
703  }
704
705  /// \brief Specify that this unqualified-id was parsed as an
706  /// operator-function-id.
707  ///
708  /// \param OperatorLoc the location of the 'operator' keyword.
709  ///
710  /// \param Op the overloaded operator.
711  ///
712  /// \param SymbolLocations the locations of the individual operator symbols
713  /// in the operator.
714  void setOperatorFunctionId(SourceLocation OperatorLoc,
715                             OverloadedOperatorKind Op,
716                             SourceLocation SymbolLocations[3]);
717
718  /// \brief Specify that this unqualified-id was parsed as a
719  /// conversion-function-id.
720  ///
721  /// \param OperatorLoc the location of the 'operator' keyword.
722  ///
723  /// \param Ty the type to which this conversion function is converting.
724  ///
725  /// \param EndLoc the location of the last token that makes up the type name.
726  void setConversionFunctionId(SourceLocation OperatorLoc,
727                               ParsedType Ty,
728                               SourceLocation EndLoc) {
729    Kind = IK_ConversionFunctionId;
730    StartLocation = OperatorLoc;
731    EndLocation = EndLoc;
732    ConversionFunctionId = Ty;
733  }
734
735  /// \brief Specific that this unqualified-id was parsed as a
736  /// literal-operator-id.
737  ///
738  /// \param Id the parsed identifier.
739  ///
740  /// \param OpLoc the location of the 'operator' keyword.
741  ///
742  /// \param IdLoc the location of the identifier.
743  void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
744                              SourceLocation IdLoc) {
745    Kind = IK_LiteralOperatorId;
746    Identifier = const_cast<IdentifierInfo *>(Id);
747    StartLocation = OpLoc;
748    EndLocation = IdLoc;
749  }
750
751  /// \brief Specify that this unqualified-id was parsed as a constructor name.
752  ///
753  /// \param ClassType the class type referred to by the constructor name.
754  ///
755  /// \param ClassNameLoc the location of the class name.
756  ///
757  /// \param EndLoc the location of the last token that makes up the type name.
758  void setConstructorName(ParsedType ClassType,
759                          SourceLocation ClassNameLoc,
760                          SourceLocation EndLoc) {
761    Kind = IK_ConstructorName;
762    StartLocation = ClassNameLoc;
763    EndLocation = EndLoc;
764    ConstructorName = ClassType;
765  }
766
767  /// \brief Specify that this unqualified-id was parsed as a
768  /// template-id that names a constructor.
769  ///
770  /// \param TemplateId the template-id annotation that describes the parsed
771  /// template-id. This UnqualifiedId instance will take ownership of the
772  /// \p TemplateId and will free it on destruction.
773  void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
774
775  /// \brief Specify that this unqualified-id was parsed as a destructor name.
776  ///
777  /// \param TildeLoc the location of the '~' that introduces the destructor
778  /// name.
779  ///
780  /// \param ClassType the name of the class referred to by the destructor name.
781  void setDestructorName(SourceLocation TildeLoc,
782                         ParsedType ClassType,
783                         SourceLocation EndLoc) {
784    Kind = IK_DestructorName;
785    StartLocation = TildeLoc;
786    EndLocation = EndLoc;
787    DestructorName = ClassType;
788  }
789
790  /// \brief Specify that this unqualified-id was parsed as a template-id.
791  ///
792  /// \param TemplateId the template-id annotation that describes the parsed
793  /// template-id. This UnqualifiedId instance will take ownership of the
794  /// \p TemplateId and will free it on destruction.
795  void setTemplateId(TemplateIdAnnotation *TemplateId);
796
797  /// \brief Return the source range that covers this unqualified-id.
798  SourceRange getSourceRange() const {
799    return SourceRange(StartLocation, EndLocation);
800  }
801};
802
803/// CachedTokens - A set of tokens that has been cached for later
804/// parsing.
805typedef llvm::SmallVector<Token, 4> CachedTokens;
806
807/// DeclaratorChunk - One instance of this struct is used for each type in a
808/// declarator that is parsed.
809///
810/// This is intended to be a small value object.
811struct DeclaratorChunk {
812  enum {
813    Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren
814  } Kind;
815
816  /// Loc - The place where this type was defined.
817  SourceLocation Loc;
818  /// EndLoc - If valid, the place where this chunck ends.
819  SourceLocation EndLoc;
820
821  struct TypeInfoCommon {
822    AttributeList *AttrList;
823  };
824
825  struct PointerTypeInfo : TypeInfoCommon {
826    /// The type qualifiers: const/volatile/restrict.
827    unsigned TypeQuals : 3;
828
829    /// The location of the const-qualifier, if any.
830    unsigned ConstQualLoc;
831
832    /// The location of the volatile-qualifier, if any.
833    unsigned VolatileQualLoc;
834
835    /// The location of the restrict-qualifier, if any.
836    unsigned RestrictQualLoc;
837
838    void destroy() {
839    }
840  };
841
842  struct ReferenceTypeInfo : TypeInfoCommon {
843    /// The type qualifier: restrict. [GNU] C++ extension
844    bool HasRestrict : 1;
845    /// True if this is an lvalue reference, false if it's an rvalue reference.
846    bool LValueRef : 1;
847    void destroy() {
848    }
849  };
850
851  struct ArrayTypeInfo : TypeInfoCommon {
852    /// The type qualifiers for the array: const/volatile/restrict.
853    unsigned TypeQuals : 3;
854
855    /// True if this dimension included the 'static' keyword.
856    bool hasStatic : 1;
857
858    /// True if this dimension was [*].  In this case, NumElts is null.
859    bool isStar : 1;
860
861    /// This is the size of the array, or null if [] or [*] was specified.
862    /// Since the parser is multi-purpose, and we don't want to impose a root
863    /// expression class on all clients, NumElts is untyped.
864    Expr *NumElts;
865
866    void destroy() {}
867  };
868
869  /// ParamInfo - An array of paraminfo objects is allocated whenever a function
870  /// declarator is parsed.  There are two interesting styles of arguments here:
871  /// K&R-style identifier lists and parameter type lists.  K&R-style identifier
872  /// lists will have information about the identifier, but no type information.
873  /// Parameter type lists will have type info (if the actions module provides
874  /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
875  struct ParamInfo {
876    IdentifierInfo *Ident;
877    SourceLocation IdentLoc;
878    Decl *Param;
879
880    /// DefaultArgTokens - When the parameter's default argument
881    /// cannot be parsed immediately (because it occurs within the
882    /// declaration of a member function), it will be stored here as a
883    /// sequence of tokens to be parsed once the class definition is
884    /// complete. Non-NULL indicates that there is a default argument.
885    CachedTokens *DefaultArgTokens;
886
887    ParamInfo() {}
888    ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
889              Decl *param,
890              CachedTokens *DefArgTokens = 0)
891      : Ident(ident), IdentLoc(iloc), Param(param),
892        DefaultArgTokens(DefArgTokens) {}
893  };
894
895  struct TypeAndRange {
896    ParsedType Ty;
897    SourceRange Range;
898  };
899
900  struct FunctionTypeInfo : TypeInfoCommon {
901    /// hasPrototype - This is true if the function had at least one typed
902    /// argument.  If the function is () or (a,b,c), then it has no prototype,
903    /// and is treated as a K&R-style function.
904    unsigned hasPrototype : 1;
905
906    /// isVariadic - If this function has a prototype, and if that
907    /// proto ends with ',...)', this is true. When true, EllipsisLoc
908    /// contains the location of the ellipsis.
909    unsigned isVariadic : 1;
910
911    /// \brief Whether the ref-qualifier (if any) is an lvalue reference.
912    /// Otherwise, it's an rvalue reference.
913    unsigned RefQualifierIsLValueRef : 1;
914
915    /// The type qualifiers: const/volatile/restrict.
916    /// The qualifier bitmask values are the same as in QualType.
917    unsigned TypeQuals : 3;
918
919    /// hasExceptionSpec - True if the function has an exception specification.
920    unsigned hasExceptionSpec : 1;
921
922    /// hasAnyExceptionSpec - True if the function has a throw(...) specifier.
923    unsigned hasAnyExceptionSpec : 1;
924
925    /// DeleteArgInfo - If this is true, we need to delete[] ArgInfo.
926    unsigned DeleteArgInfo : 1;
927
928    /// When isVariadic is true, the location of the ellipsis in the source.
929    unsigned EllipsisLoc;
930
931    /// NumArgs - This is the number of formal arguments provided for the
932    /// declarator.
933    unsigned NumArgs;
934
935    /// NumExceptions - This is the number of types in the exception-decl, if
936    /// the function has one.
937    unsigned NumExceptions;
938
939    /// \brief The location of the ref-qualifier, if any.
940    ///
941    /// If this is an invalid location, there is no ref-qualifier.
942    unsigned RefQualifierLoc;
943
944    /// ThrowLoc - When hasExceptionSpec is true, the location of the throw
945    /// keyword introducing the spec.
946    unsigned ThrowLoc;
947
948    /// ArgInfo - This is a pointer to a new[]'d array of ParamInfo objects that
949    /// describe the arguments for this function declarator.  This is null if
950    /// there are no arguments specified.
951    ParamInfo *ArgInfo;
952
953    /// Exceptions - This is a pointer to a new[]'d array of TypeAndRange
954    /// objects that contain the types in the function's exception
955    /// specification and their locations.
956    TypeAndRange *Exceptions;
957
958    /// TrailingReturnType - If this isn't null, it's the trailing return type
959    /// specified. This is actually a ParsedType, but stored as void* to
960    /// allow union storage.
961    void *TrailingReturnType;
962
963    /// freeArgs - reset the argument list to having zero arguments.  This is
964    /// used in various places for error recovery.
965    void freeArgs() {
966      if (DeleteArgInfo) {
967        delete[] ArgInfo;
968        DeleteArgInfo = false;
969      }
970      NumArgs = 0;
971    }
972
973    void destroy() {
974      if (DeleteArgInfo)
975        delete[] ArgInfo;
976      delete[] Exceptions;
977    }
978
979    /// isKNRPrototype - Return true if this is a K&R style identifier list,
980    /// like "void foo(a,b,c)".  In a function definition, this will be followed
981    /// by the argument type definitions.
982    bool isKNRPrototype() const {
983      return !hasPrototype && NumArgs != 0;
984    }
985
986    SourceLocation getEllipsisLoc() const {
987      return SourceLocation::getFromRawEncoding(EllipsisLoc);
988    }
989    SourceLocation getThrowLoc() const {
990      return SourceLocation::getFromRawEncoding(ThrowLoc);
991    }
992
993    /// \brief Retrieve the location of the ref-qualifier, if any.
994    SourceLocation getRefQualifierLoc() const {
995      return SourceLocation::getFromRawEncoding(RefQualifierLoc);
996    }
997
998    /// \brief Determine whether this function declaration contains a
999    /// ref-qualifier.
1000    bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1001  };
1002
1003  struct BlockPointerTypeInfo : TypeInfoCommon {
1004    /// For now, sema will catch these as invalid.
1005    /// The type qualifiers: const/volatile/restrict.
1006    unsigned TypeQuals : 3;
1007
1008    void destroy() {
1009    }
1010  };
1011
1012  struct MemberPointerTypeInfo : TypeInfoCommon {
1013    /// The type qualifiers: const/volatile/restrict.
1014    unsigned TypeQuals : 3;
1015    // CXXScopeSpec has a constructor, so it can't be a direct member.
1016    // So we need some pointer-aligned storage and a bit of trickery.
1017    union {
1018      void *Aligner;
1019      char Mem[sizeof(CXXScopeSpec)];
1020    } ScopeMem;
1021    CXXScopeSpec &Scope() {
1022      return *reinterpret_cast<CXXScopeSpec*>(ScopeMem.Mem);
1023    }
1024    const CXXScopeSpec &Scope() const {
1025      return *reinterpret_cast<const CXXScopeSpec*>(ScopeMem.Mem);
1026    }
1027    void destroy() {
1028      Scope().~CXXScopeSpec();
1029    }
1030  };
1031
1032  union {
1033    TypeInfoCommon        Common;
1034    PointerTypeInfo       Ptr;
1035    ReferenceTypeInfo     Ref;
1036    ArrayTypeInfo         Arr;
1037    FunctionTypeInfo      Fun;
1038    BlockPointerTypeInfo  Cls;
1039    MemberPointerTypeInfo Mem;
1040  };
1041
1042  void destroy() {
1043    switch (Kind) {
1044    default: assert(0 && "Unknown decl type!");
1045    case DeclaratorChunk::Function:      return Fun.destroy();
1046    case DeclaratorChunk::Pointer:       return Ptr.destroy();
1047    case DeclaratorChunk::BlockPointer:  return Cls.destroy();
1048    case DeclaratorChunk::Reference:     return Ref.destroy();
1049    case DeclaratorChunk::Array:         return Arr.destroy();
1050    case DeclaratorChunk::MemberPointer: return Mem.destroy();
1051    case DeclaratorChunk::Paren:         return;
1052    }
1053  }
1054
1055  /// getAttrs - If there are attributes applied to this declaratorchunk, return
1056  /// them.
1057  const AttributeList *getAttrs() const {
1058    return Common.AttrList;
1059  }
1060
1061  AttributeList *&getAttrListRef() {
1062    return Common.AttrList;
1063  }
1064
1065  /// getPointer - Return a DeclaratorChunk for a pointer.
1066  ///
1067  static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1068                                    SourceLocation ConstQualLoc,
1069                                    SourceLocation VolatileQualLoc,
1070                                    SourceLocation RestrictQualLoc,
1071                                    const ParsedAttributes &attrs) {
1072    DeclaratorChunk I;
1073    I.Kind                = Pointer;
1074    I.Loc                 = Loc;
1075    I.Ptr.TypeQuals       = TypeQuals;
1076    I.Ptr.ConstQualLoc    = ConstQualLoc.getRawEncoding();
1077    I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1078    I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1079    I.Ptr.AttrList        = attrs.getList();
1080    return I;
1081  }
1082
1083  /// getReference - Return a DeclaratorChunk for a reference.
1084  ///
1085  static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1086                                      const ParsedAttributes &attrs,
1087                                      bool lvalue) {
1088    DeclaratorChunk I;
1089    I.Kind            = Reference;
1090    I.Loc             = Loc;
1091    I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1092    I.Ref.LValueRef   = lvalue;
1093    I.Ref.AttrList    = attrs.getList();
1094    return I;
1095  }
1096
1097  /// getArray - Return a DeclaratorChunk for an array.
1098  ///
1099  static DeclaratorChunk getArray(unsigned TypeQuals,
1100                                  const ParsedAttributes &attrs,
1101                                  bool isStatic, bool isStar, Expr *NumElts,
1102                                  SourceLocation LBLoc, SourceLocation RBLoc) {
1103    DeclaratorChunk I;
1104    I.Kind          = Array;
1105    I.Loc           = LBLoc;
1106    I.EndLoc        = RBLoc;
1107    I.Arr.AttrList  = attrs.getList();
1108    I.Arr.TypeQuals = TypeQuals;
1109    I.Arr.hasStatic = isStatic;
1110    I.Arr.isStar    = isStar;
1111    I.Arr.NumElts   = NumElts;
1112    return I;
1113  }
1114
1115  /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1116  /// "TheDeclarator" is the declarator that this will be added to.
1117  static DeclaratorChunk getFunction(const ParsedAttributes &attrs,
1118                                     bool hasProto, bool isVariadic,
1119                                     SourceLocation EllipsisLoc,
1120                                     ParamInfo *ArgInfo, unsigned NumArgs,
1121                                     unsigned TypeQuals,
1122                                     bool RefQualifierIsLvalueRef,
1123                                     SourceLocation RefQualifierLoc,
1124                                     bool hasExceptionSpec,
1125                                     SourceLocation ThrowLoc,
1126                                     bool hasAnyExceptionSpec,
1127                                     ParsedType *Exceptions,
1128                                     SourceRange *ExceptionRanges,
1129                                     unsigned NumExceptions,
1130                                     SourceLocation LPLoc, SourceLocation RPLoc,
1131                                     Declarator &TheDeclarator,
1132                                     ParsedType TrailingReturnType = ParsedType());
1133
1134  /// getBlockPointer - Return a DeclaratorChunk for a block.
1135  ///
1136  static DeclaratorChunk getBlockPointer(unsigned TypeQuals, SourceLocation Loc,
1137                                         const ParsedAttributes &attrs) {
1138    DeclaratorChunk I;
1139    I.Kind          = BlockPointer;
1140    I.Loc           = Loc;
1141    I.Cls.TypeQuals = TypeQuals;
1142    I.Cls.AttrList  = attrs.getList();
1143    return I;
1144  }
1145
1146  static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1147                                          unsigned TypeQuals,
1148                                          SourceLocation Loc,
1149                                          const ParsedAttributes &attrs) {
1150    DeclaratorChunk I;
1151    I.Kind          = MemberPointer;
1152    I.Loc           = Loc;
1153    I.Mem.TypeQuals = TypeQuals;
1154    I.Mem.AttrList  = attrs.getList();
1155    new (I.Mem.ScopeMem.Mem) CXXScopeSpec(SS);
1156    return I;
1157  }
1158
1159  /// getParen - Return a DeclaratorChunk for a paren.
1160  ///
1161  static DeclaratorChunk getParen(SourceLocation LParenLoc,
1162                                  SourceLocation RParenLoc) {
1163    DeclaratorChunk I;
1164    I.Kind          = Paren;
1165    I.Loc           = LParenLoc;
1166    I.EndLoc        = RParenLoc;
1167    I.Common.AttrList = 0;
1168    return I;
1169  }
1170
1171};
1172
1173/// Declarator - Information about one declarator, including the parsed type
1174/// information and the identifier.  When the declarator is fully formed, this
1175/// is turned into the appropriate Decl object.
1176///
1177/// Declarators come in two types: normal declarators and abstract declarators.
1178/// Abstract declarators are used when parsing types, and don't have an
1179/// identifier.  Normal declarators do have ID's.
1180///
1181/// Instances of this class should be a transient object that lives on the
1182/// stack, not objects that are allocated in large quantities on the heap.
1183class Declarator {
1184public:
1185  enum TheContext {
1186    FileContext,         // File scope declaration.
1187    PrototypeContext,    // Within a function prototype.
1188    KNRTypeListContext,  // K&R type definition list for formals.
1189    TypeNameContext,     // Abstract declarator for types.
1190    MemberContext,       // Struct/Union field.
1191    BlockContext,        // Declaration within a block in a function.
1192    ForContext,          // Declaration within first part of a for loop.
1193    ConditionContext,    // Condition declaration in a C++ if/switch/while/for.
1194    TemplateParamContext,// Within a template parameter list.
1195    CXXCatchContext,     // C++ catch exception-declaration
1196    BlockLiteralContext,  // Block literal declarator.
1197    TemplateTypeArgContext // Template type argument.
1198  };
1199
1200private:
1201  const DeclSpec &DS;
1202  CXXScopeSpec SS;
1203  UnqualifiedId Name;
1204  SourceRange Range;
1205
1206  /// Context - Where we are parsing this declarator.
1207  ///
1208  TheContext Context;
1209
1210  /// DeclTypeInfo - This holds each type that the declarator includes as it is
1211  /// parsed.  This is pushed from the identifier out, which means that element
1212  /// #0 will be the most closely bound to the identifier, and
1213  /// DeclTypeInfo.back() will be the least closely bound.
1214  llvm::SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1215
1216  /// InvalidType - Set by Sema::GetTypeForDeclarator().
1217  bool InvalidType : 1;
1218
1219  /// GroupingParens - Set by Parser::ParseParenDeclarator().
1220  bool GroupingParens : 1;
1221
1222  /// AttrList - Attributes.
1223  AttributeList *AttrList;
1224
1225  /// AsmLabel - The asm label, if specified.
1226  Expr *AsmLabel;
1227
1228  /// InlineParams - This is a local array used for the first function decl
1229  /// chunk to avoid going to the heap for the common case when we have one
1230  /// function chunk in the declarator.
1231  DeclaratorChunk::ParamInfo InlineParams[16];
1232  bool InlineParamsUsed;
1233
1234  /// Extension - true if the declaration is preceded by __extension__.
1235  bool Extension : 1;
1236
1237  /// \brief If provided, the source location of the ellipsis used to describe
1238  /// this declarator as a parameter pack.
1239  SourceLocation EllipsisLoc;
1240
1241  friend struct DeclaratorChunk;
1242
1243public:
1244  Declarator(const DeclSpec &ds, TheContext C)
1245    : DS(ds), Range(ds.getSourceRange()), Context(C),
1246      InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1247      GroupingParens(false), AttrList(0), AsmLabel(0),
1248      InlineParamsUsed(false), Extension(false) {
1249  }
1250
1251  ~Declarator() {
1252    clear();
1253  }
1254
1255  /// getDeclSpec - Return the declaration-specifier that this declarator was
1256  /// declared with.
1257  const DeclSpec &getDeclSpec() const { return DS; }
1258
1259  /// getMutableDeclSpec - Return a non-const version of the DeclSpec.  This
1260  /// should be used with extreme care: declspecs can often be shared between
1261  /// multiple declarators, so mutating the DeclSpec affects all of the
1262  /// Declarators.  This should only be done when the declspec is known to not
1263  /// be shared or when in error recovery etc.
1264  DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1265
1266  /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1267  /// nested-name-specifier) that is part of the declarator-id.
1268  const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1269  CXXScopeSpec &getCXXScopeSpec() { return SS; }
1270
1271  /// \brief Retrieve the name specified by this declarator.
1272  UnqualifiedId &getName() { return Name; }
1273
1274  TheContext getContext() const { return Context; }
1275
1276  /// getSourceRange - Get the source range that spans this declarator.
1277  const SourceRange &getSourceRange() const { return Range; }
1278
1279  void SetSourceRange(SourceRange R) { Range = R; }
1280  /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1281  /// invalid.
1282  void SetRangeBegin(SourceLocation Loc) {
1283    if (!Loc.isInvalid())
1284      Range.setBegin(Loc);
1285  }
1286  /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1287  void SetRangeEnd(SourceLocation Loc) {
1288    if (!Loc.isInvalid())
1289      Range.setEnd(Loc);
1290  }
1291  /// ExtendWithDeclSpec - Extend the declarator source range to include the
1292  /// given declspec, unless its location is invalid. Adopts the range start if
1293  /// the current range start is invalid.
1294  void ExtendWithDeclSpec(const DeclSpec &DS) {
1295    const SourceRange &SR = DS.getSourceRange();
1296    if (Range.getBegin().isInvalid())
1297      Range.setBegin(SR.getBegin());
1298    if (!SR.getEnd().isInvalid())
1299      Range.setEnd(SR.getEnd());
1300  }
1301
1302  /// clear - Reset the contents of this Declarator.
1303  void clear() {
1304    SS.clear();
1305    Name.clear();
1306    Range = DS.getSourceRange();
1307
1308    for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1309      DeclTypeInfo[i].destroy();
1310    DeclTypeInfo.clear();
1311    AttrList = 0;
1312    AsmLabel = 0;
1313    InlineParamsUsed = false;
1314  }
1315
1316  /// mayOmitIdentifier - Return true if the identifier is either optional or
1317  /// not allowed.  This is true for typenames, prototypes, and template
1318  /// parameter lists.
1319  bool mayOmitIdentifier() const {
1320    return Context == TypeNameContext || Context == PrototypeContext ||
1321           Context == TemplateParamContext || Context == CXXCatchContext ||
1322           Context == BlockLiteralContext || Context == TemplateTypeArgContext;
1323  }
1324
1325  /// mayHaveIdentifier - Return true if the identifier is either optional or
1326  /// required.  This is true for normal declarators and prototypes, but not
1327  /// typenames.
1328  bool mayHaveIdentifier() const {
1329    return Context != TypeNameContext && Context != BlockLiteralContext &&
1330           Context != TemplateTypeArgContext;
1331  }
1332
1333  /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
1334  /// followed by a C++ direct initializer, e.g. "int x(1);".
1335  bool mayBeFollowedByCXXDirectInit() const {
1336    return !hasGroupingParens() &&
1337           (Context == FileContext  ||
1338            Context == BlockContext ||
1339            Context == ForContext);
1340  }
1341
1342  /// isPastIdentifier - Return true if we have parsed beyond the point where
1343  /// the
1344  bool isPastIdentifier() const { return Name.isValid(); }
1345
1346  /// hasName - Whether this declarator has a name, which might be an
1347  /// identifier (accessible via getIdentifier()) or some kind of
1348  /// special C++ name (constructor, destructor, etc.).
1349  bool hasName() const {
1350    return Name.getKind() != UnqualifiedId::IK_Identifier || Name.Identifier;
1351  }
1352
1353  IdentifierInfo *getIdentifier() const {
1354    if (Name.getKind() == UnqualifiedId::IK_Identifier)
1355      return Name.Identifier;
1356
1357    return 0;
1358  }
1359  SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
1360
1361  /// \brief Set the name of this declarator to be the given identifier.
1362  void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
1363    Name.setIdentifier(Id, IdLoc);
1364  }
1365
1366  /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
1367  /// EndLoc, which should be the last token of the chunk.
1368  void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
1369    DeclTypeInfo.push_back(TI);
1370    if (!EndLoc.isInvalid())
1371      SetRangeEnd(EndLoc);
1372  }
1373
1374  /// AddInnermostTypeInfo - Add a new innermost chunk to this declarator.
1375  void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
1376    DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
1377  }
1378
1379  /// getNumTypeObjects() - Return the number of types applied to this
1380  /// declarator.
1381  unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
1382
1383  /// Return the specified TypeInfo from this declarator.  TypeInfo #0 is
1384  /// closest to the identifier.
1385  const DeclaratorChunk &getTypeObject(unsigned i) const {
1386    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1387    return DeclTypeInfo[i];
1388  }
1389  DeclaratorChunk &getTypeObject(unsigned i) {
1390    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1391    return DeclTypeInfo[i];
1392  }
1393
1394  void DropFirstTypeObject()
1395  {
1396    assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
1397    DeclTypeInfo.front().destroy();
1398    DeclTypeInfo.erase(DeclTypeInfo.begin());
1399  }
1400
1401  /// isFunctionDeclarator - This method returns true if the declarator
1402  /// is a function declarator (looking through parentheses).
1403  /// If true is returned, then the reference type parameter idx is
1404  /// assigned with the index of the declaration chunk.
1405  bool isFunctionDeclarator(unsigned& idx) const {
1406    for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1407      switch (DeclTypeInfo[i].Kind) {
1408      case DeclaratorChunk::Function:
1409        idx = i;
1410        return true;
1411      case DeclaratorChunk::Paren:
1412        continue;
1413      case DeclaratorChunk::Pointer:
1414      case DeclaratorChunk::Reference:
1415      case DeclaratorChunk::Array:
1416      case DeclaratorChunk::BlockPointer:
1417      case DeclaratorChunk::MemberPointer:
1418        return false;
1419      }
1420      llvm_unreachable("Invalid type chunk");
1421      return false;
1422    }
1423    return false;
1424  }
1425
1426  /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
1427  /// this method returns true if the identifier is a function declarator
1428  /// (looking through parentheses).
1429  bool isFunctionDeclarator() const {
1430    unsigned index;
1431    return isFunctionDeclarator(index);
1432  }
1433
1434  /// getFunctionTypeInfo - Retrieves the function type info object
1435  /// (looking through parentheses).
1436  DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
1437    assert(isFunctionDeclarator() && "Not a function declarator!");
1438    unsigned index = 0;
1439    isFunctionDeclarator(index);
1440    return DeclTypeInfo[index].Fun;
1441  }
1442
1443  /// getFunctionTypeInfo - Retrieves the function type info object
1444  /// (looking through parentheses).
1445  const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
1446    return const_cast<Declarator*>(this)->getFunctionTypeInfo();
1447  }
1448
1449  /// AddAttributes - simply adds the attribute list to the Declarator.
1450  /// These examples both add 3 attributes to "var":
1451  ///  short int var __attribute__((aligned(16),common,deprecated));
1452  ///  short int x, __attribute__((aligned(16)) var
1453  ///                                 __attribute__((common,deprecated));
1454  ///
1455  /// Also extends the range of the declarator.
1456  void addAttributes(AttributeList *alist, SourceLocation LastLoc) {
1457    AttrList = addAttributeLists(AttrList, alist);
1458
1459    if (!LastLoc.isInvalid())
1460      SetRangeEnd(LastLoc);
1461  }
1462
1463  void addAttributes(const ParsedAttributes &attrs) {
1464    addAttributes(attrs.getList(), SourceLocation());
1465  }
1466
1467  const AttributeList *getAttributes() const { return AttrList; }
1468  AttributeList *getAttributes() { return AttrList; }
1469
1470  AttributeList *&getAttrListRef() { return AttrList; }
1471
1472  /// hasAttributes - do we contain any attributes?
1473  bool hasAttributes() const {
1474    if (getAttributes() || getDeclSpec().hasAttributes()) return true;
1475    for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
1476      if (getTypeObject(i).getAttrs())
1477        return true;
1478    return false;
1479  }
1480
1481  void setAsmLabel(Expr *E) { AsmLabel = E; }
1482  Expr *getAsmLabel() const { return AsmLabel; }
1483
1484  void setExtension(bool Val = true) { Extension = Val; }
1485  bool getExtension() const { return Extension; }
1486
1487  void setInvalidType(bool Val = true) { InvalidType = Val; }
1488  bool isInvalidType() const {
1489    return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
1490  }
1491
1492  void setGroupingParens(bool flag) { GroupingParens = flag; }
1493  bool hasGroupingParens() const { return GroupingParens; }
1494
1495  bool hasEllipsis() const { return EllipsisLoc.isValid(); }
1496  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
1497  void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
1498};
1499
1500/// FieldDeclarator - This little struct is used to capture information about
1501/// structure field declarators, which is basically just a bitfield size.
1502struct FieldDeclarator {
1503  Declarator D;
1504  Expr *BitfieldSize;
1505  explicit FieldDeclarator(DeclSpec &DS) : D(DS, Declarator::MemberContext) {
1506    BitfieldSize = 0;
1507  }
1508};
1509
1510/// VirtSpecifiers - Represents a C++0x virt-specifier-seq.
1511class VirtSpecifiers {
1512public:
1513  enum Specifier {
1514    VS_None = 0,
1515    VS_Override = 1,
1516    VS_Final = 2,
1517    VS_New = 4
1518  };
1519
1520  VirtSpecifiers() : Specifiers(0) { }
1521
1522  bool SetSpecifier(Specifier VS, SourceLocation Loc,
1523                    const char *&PrevSpec);
1524
1525  bool isOverrideSpecified() const { return Specifiers & VS_Override; }
1526  SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
1527
1528  bool isFinalSpecified() const { return Specifiers & VS_Final; }
1529  SourceLocation getFinalLoc() const { return VS_finalLoc; }
1530
1531  bool isNewSpecified() const { return Specifiers & VS_New; }
1532  SourceLocation getNewLoc() const { return VS_newLoc; }
1533
1534  void clear() { Specifiers = 0; }
1535
1536  static const char *getSpecifierName(Specifier VS);
1537
1538private:
1539  unsigned Specifiers;
1540
1541  SourceLocation VS_overrideLoc, VS_finalLoc, VS_newLoc;
1542};
1543
1544/// ClassVirtSpecifiers - Represents a C++0x class-virt-specifier-seq.
1545class ClassVirtSpecifiers {
1546public:
1547  enum Specifier {
1548    CVS_None = 0,
1549    CVS_Final = 1,
1550    CVS_Explicit = 2
1551  };
1552
1553  ClassVirtSpecifiers() : Specifiers(0) { }
1554
1555  bool SetSpecifier(Specifier CVS, SourceLocation Loc,
1556                    const char *&PrevSpec);
1557
1558  bool isFinalSpecified() const { return Specifiers & CVS_Final; }
1559  SourceLocation getFinalLoc() const { return CVS_finalLoc; }
1560
1561  bool isExplicitSpecified() const { return Specifiers & CVS_Explicit; }
1562  SourceLocation getExplicitLoc() const { return CVS_explicitLoc; }
1563
1564  static const char *getSpecifierName(Specifier CVS);
1565
1566private:
1567  unsigned Specifiers;
1568
1569  SourceLocation CVS_finalLoc, CVS_explicitLoc;
1570};
1571
1572} // end namespace clang
1573
1574#endif
1575