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