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