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