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