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