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