DeclSpec.h revision e462c60ac3365d3302b7d0a566c5cb7dbe0e5ae3
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  struct OFI {
825    /// \brief The kind of overloaded operator.
826    OverloadedOperatorKind Operator;
827
828    /// \brief The source locations of the individual tokens that name
829    /// the operator, e.g., the "new", "[", and "]" tokens in
830    /// operator new [].
831    ///
832    /// Different operators have different numbers of tokens in their name,
833    /// up to three. Any remaining source locations in this array will be
834    /// set to an invalid value for operators with fewer than three tokens.
835    unsigned SymbolLocations[3];
836  };
837
838  /// \brief Anonymous union that holds extra data associated with the
839  /// parsed unqualified-id.
840  union {
841    /// \brief When Kind == IK_Identifier, the parsed identifier, or when Kind
842    /// == IK_UserLiteralId, the identifier suffix.
843    IdentifierInfo *Identifier;
844
845    /// \brief When Kind == IK_OperatorFunctionId, the overloaded operator
846    /// that we parsed.
847    struct OFI OperatorFunctionId;
848
849    /// \brief When Kind == IK_ConversionFunctionId, the type that the
850    /// conversion function names.
851    UnionParsedType ConversionFunctionId;
852
853    /// \brief When Kind == IK_ConstructorName, the class-name of the type
854    /// whose constructor is being referenced.
855    UnionParsedType ConstructorName;
856
857    /// \brief When Kind == IK_DestructorName, the type referred to by the
858    /// class-name.
859    UnionParsedType DestructorName;
860
861    /// \brief When Kind == IK_TemplateId or IK_ConstructorTemplateId,
862    /// the template-id annotation that contains the template name and
863    /// template arguments.
864    TemplateIdAnnotation *TemplateId;
865  };
866
867  /// \brief The location of the first token that describes this unqualified-id,
868  /// which will be the location of the identifier, "operator" keyword,
869  /// tilde (for a destructor), or the template name of a template-id.
870  SourceLocation StartLocation;
871
872  /// \brief The location of the last token that describes this unqualified-id.
873  SourceLocation EndLocation;
874
875  UnqualifiedId() : Kind(IK_Identifier), Identifier(0) { }
876
877  /// \brief Clear out this unqualified-id, setting it to default (invalid)
878  /// state.
879  void clear() {
880    Kind = IK_Identifier;
881    Identifier = 0;
882    StartLocation = SourceLocation();
883    EndLocation = SourceLocation();
884  }
885
886  /// \brief Determine whether this unqualified-id refers to a valid name.
887  bool isValid() const { return StartLocation.isValid(); }
888
889  /// \brief Determine whether this unqualified-id refers to an invalid name.
890  bool isInvalid() const { return !isValid(); }
891
892  /// \brief Determine what kind of name we have.
893  IdKind getKind() const { return Kind; }
894  void setKind(IdKind kind) { Kind = kind; }
895
896  /// \brief Specify that this unqualified-id was parsed as an identifier.
897  ///
898  /// \param Id the parsed identifier.
899  /// \param IdLoc the location of the parsed identifier.
900  void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
901    Kind = IK_Identifier;
902    Identifier = const_cast<IdentifierInfo *>(Id);
903    StartLocation = EndLocation = IdLoc;
904  }
905
906  /// \brief Specify that this unqualified-id was parsed as an
907  /// operator-function-id.
908  ///
909  /// \param OperatorLoc the location of the 'operator' keyword.
910  ///
911  /// \param Op the overloaded operator.
912  ///
913  /// \param SymbolLocations the locations of the individual operator symbols
914  /// in the operator.
915  void setOperatorFunctionId(SourceLocation OperatorLoc,
916                             OverloadedOperatorKind Op,
917                             SourceLocation SymbolLocations[3]);
918
919  /// \brief Specify that this unqualified-id was parsed as a
920  /// conversion-function-id.
921  ///
922  /// \param OperatorLoc the location of the 'operator' keyword.
923  ///
924  /// \param Ty the type to which this conversion function is converting.
925  ///
926  /// \param EndLoc the location of the last token that makes up the type name.
927  void setConversionFunctionId(SourceLocation OperatorLoc,
928                               ParsedType Ty,
929                               SourceLocation EndLoc) {
930    Kind = IK_ConversionFunctionId;
931    StartLocation = OperatorLoc;
932    EndLocation = EndLoc;
933    ConversionFunctionId = Ty;
934  }
935
936  /// \brief Specific that this unqualified-id was parsed as a
937  /// literal-operator-id.
938  ///
939  /// \param Id the parsed identifier.
940  ///
941  /// \param OpLoc the location of the 'operator' keyword.
942  ///
943  /// \param IdLoc the location of the identifier.
944  void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
945                              SourceLocation IdLoc) {
946    Kind = IK_LiteralOperatorId;
947    Identifier = const_cast<IdentifierInfo *>(Id);
948    StartLocation = OpLoc;
949    EndLocation = IdLoc;
950  }
951
952  /// \brief Specify that this unqualified-id was parsed as a constructor name.
953  ///
954  /// \param ClassType the class type referred to by the constructor name.
955  ///
956  /// \param ClassNameLoc the location of the class name.
957  ///
958  /// \param EndLoc the location of the last token that makes up the type name.
959  void setConstructorName(ParsedType ClassType,
960                          SourceLocation ClassNameLoc,
961                          SourceLocation EndLoc) {
962    Kind = IK_ConstructorName;
963    StartLocation = ClassNameLoc;
964    EndLocation = EndLoc;
965    ConstructorName = ClassType;
966  }
967
968  /// \brief Specify that this unqualified-id was parsed as a
969  /// template-id that names a constructor.
970  ///
971  /// \param TemplateId the template-id annotation that describes the parsed
972  /// template-id. This UnqualifiedId instance will take ownership of the
973  /// \p TemplateId and will free it on destruction.
974  void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
975
976  /// \brief Specify that this unqualified-id was parsed as a destructor name.
977  ///
978  /// \param TildeLoc the location of the '~' that introduces the destructor
979  /// name.
980  ///
981  /// \param ClassType the name of the class referred to by the destructor name.
982  void setDestructorName(SourceLocation TildeLoc,
983                         ParsedType ClassType,
984                         SourceLocation EndLoc) {
985    Kind = IK_DestructorName;
986    StartLocation = TildeLoc;
987    EndLocation = EndLoc;
988    DestructorName = ClassType;
989  }
990
991  /// \brief Specify that this unqualified-id was parsed as a template-id.
992  ///
993  /// \param TemplateId the template-id annotation that describes the parsed
994  /// template-id. This UnqualifiedId instance will take ownership of the
995  /// \p TemplateId and will free it on destruction.
996  void setTemplateId(TemplateIdAnnotation *TemplateId);
997
998  /// \brief Return the source range that covers this unqualified-id.
999  SourceRange getSourceRange() const LLVM_READONLY {
1000    return SourceRange(StartLocation, EndLocation);
1001  }
1002  SourceLocation getLocStart() const LLVM_READONLY { return StartLocation; }
1003  SourceLocation getLocEnd() const LLVM_READONLY { return EndLocation; }
1004};
1005
1006/// \brief A set of tokens that has been cached for later parsing.
1007typedef SmallVector<Token, 4> CachedTokens;
1008
1009/// \brief One instance of this struct is used for each type in a
1010/// declarator that is parsed.
1011///
1012/// This is intended to be a small value object.
1013struct DeclaratorChunk {
1014  enum {
1015    Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren
1016  } Kind;
1017
1018  /// Loc - The place where this type was defined.
1019  SourceLocation Loc;
1020  /// EndLoc - If valid, the place where this chunck ends.
1021  SourceLocation EndLoc;
1022
1023  struct TypeInfoCommon {
1024    AttributeList *AttrList;
1025  };
1026
1027  struct PointerTypeInfo : TypeInfoCommon {
1028    /// The type qualifiers: const/volatile/restrict.
1029    unsigned TypeQuals : 3;
1030
1031    /// The location of the const-qualifier, if any.
1032    unsigned ConstQualLoc;
1033
1034    /// The location of the volatile-qualifier, if any.
1035    unsigned VolatileQualLoc;
1036
1037    /// The location of the restrict-qualifier, if any.
1038    unsigned RestrictQualLoc;
1039
1040    void destroy() {
1041    }
1042  };
1043
1044  struct ReferenceTypeInfo : TypeInfoCommon {
1045    /// The type qualifier: restrict. [GNU] C++ extension
1046    bool HasRestrict : 1;
1047    /// True if this is an lvalue reference, false if it's an rvalue reference.
1048    bool LValueRef : 1;
1049    void destroy() {
1050    }
1051  };
1052
1053  struct ArrayTypeInfo : TypeInfoCommon {
1054    /// The type qualifiers for the array: const/volatile/restrict.
1055    unsigned TypeQuals : 3;
1056
1057    /// True if this dimension included the 'static' keyword.
1058    bool hasStatic : 1;
1059
1060    /// True if this dimension was [*].  In this case, NumElts is null.
1061    bool isStar : 1;
1062
1063    /// This is the size of the array, or null if [] or [*] was specified.
1064    /// Since the parser is multi-purpose, and we don't want to impose a root
1065    /// expression class on all clients, NumElts is untyped.
1066    Expr *NumElts;
1067
1068    void destroy() {}
1069  };
1070
1071  /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1072  /// declarator is parsed.  There are two interesting styles of arguments here:
1073  /// K&R-style identifier lists and parameter type lists.  K&R-style identifier
1074  /// lists will have information about the identifier, but no type information.
1075  /// Parameter type lists will have type info (if the actions module provides
1076  /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1077  struct ParamInfo {
1078    IdentifierInfo *Ident;
1079    SourceLocation IdentLoc;
1080    Decl *Param;
1081
1082    /// DefaultArgTokens - When the parameter's default argument
1083    /// cannot be parsed immediately (because it occurs within the
1084    /// declaration of a member function), it will be stored here as a
1085    /// sequence of tokens to be parsed once the class definition is
1086    /// complete. Non-NULL indicates that there is a default argument.
1087    CachedTokens *DefaultArgTokens;
1088
1089    ParamInfo() {}
1090    ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1091              Decl *param,
1092              CachedTokens *DefArgTokens = 0)
1093      : Ident(ident), IdentLoc(iloc), Param(param),
1094        DefaultArgTokens(DefArgTokens) {}
1095  };
1096
1097  struct TypeAndRange {
1098    ParsedType Ty;
1099    SourceRange Range;
1100  };
1101
1102  struct FunctionTypeInfo : TypeInfoCommon {
1103    /// hasPrototype - This is true if the function had at least one typed
1104    /// argument.  If the function is () or (a,b,c), then it has no prototype,
1105    /// and is treated as a K&R-style function.
1106    unsigned hasPrototype : 1;
1107
1108    /// isVariadic - If this function has a prototype, and if that
1109    /// proto ends with ',...)', this is true. When true, EllipsisLoc
1110    /// contains the location of the ellipsis.
1111    unsigned isVariadic : 1;
1112
1113    /// Can this declaration be a constructor-style initializer?
1114    unsigned isAmbiguous : 1;
1115
1116    /// \brief Whether the ref-qualifier (if any) is an lvalue reference.
1117    /// Otherwise, it's an rvalue reference.
1118    unsigned RefQualifierIsLValueRef : 1;
1119
1120    /// The type qualifiers: const/volatile/restrict.
1121    /// The qualifier bitmask values are the same as in QualType.
1122    unsigned TypeQuals : 3;
1123
1124    /// ExceptionSpecType - An ExceptionSpecificationType value.
1125    unsigned ExceptionSpecType : 3;
1126
1127    /// DeleteArgInfo - If this is true, we need to delete[] ArgInfo.
1128    unsigned DeleteArgInfo : 1;
1129
1130    /// HasTrailingReturnType - If this is true, a trailing return type was
1131    /// specified.
1132    unsigned HasTrailingReturnType : 1;
1133
1134    /// The location of the left parenthesis in the source.
1135    unsigned LParenLoc;
1136
1137    /// When isVariadic is true, the location of the ellipsis in the source.
1138    unsigned EllipsisLoc;
1139
1140    /// The location of the right parenthesis in the source.
1141    unsigned RParenLoc;
1142
1143    /// NumArgs - This is the number of formal arguments provided for the
1144    /// declarator.
1145    unsigned NumArgs;
1146
1147    /// NumExceptions - This is the number of types in the dynamic-exception-
1148    /// decl, if the function has one.
1149    unsigned NumExceptions;
1150
1151    /// \brief The location of the ref-qualifier, if any.
1152    ///
1153    /// If this is an invalid location, there is no ref-qualifier.
1154    unsigned RefQualifierLoc;
1155
1156    /// \brief The location of the const-qualifier, if any.
1157    ///
1158    /// If this is an invalid location, there is no const-qualifier.
1159    unsigned ConstQualifierLoc;
1160
1161    /// \brief The location of the volatile-qualifier, if any.
1162    ///
1163    /// If this is an invalid location, there is no volatile-qualifier.
1164    unsigned VolatileQualifierLoc;
1165
1166    /// \brief The location of the 'mutable' qualifer in a lambda-declarator, if
1167    /// any.
1168    unsigned MutableLoc;
1169
1170    /// \brief The location of the keyword introducing the spec, if any.
1171    unsigned ExceptionSpecLoc;
1172
1173    /// ArgInfo - This is a pointer to a new[]'d array of ParamInfo objects that
1174    /// describe the arguments for this function declarator.  This is null if
1175    /// there are no arguments specified.
1176    ParamInfo *ArgInfo;
1177
1178    union {
1179      /// \brief Pointer to a new[]'d array of TypeAndRange objects that
1180      /// contain the types in the function's dynamic exception specification
1181      /// and their locations, if there is one.
1182      TypeAndRange *Exceptions;
1183
1184      /// \brief Pointer to the expression in the noexcept-specifier of this
1185      /// function, if it has one.
1186      Expr *NoexceptExpr;
1187    };
1188
1189    /// \brief If HasTrailingReturnType is true, this is the trailing return
1190    /// type specified.
1191    UnionParsedType TrailingReturnType;
1192
1193    /// \brief Reset the argument list to having zero arguments.
1194    ///
1195    /// This is used in various places for error recovery.
1196    void freeArgs() {
1197      if (DeleteArgInfo) {
1198        delete[] ArgInfo;
1199        DeleteArgInfo = false;
1200      }
1201      NumArgs = 0;
1202    }
1203
1204    void destroy() {
1205      if (DeleteArgInfo)
1206        delete[] ArgInfo;
1207      if (getExceptionSpecType() == EST_Dynamic)
1208        delete[] Exceptions;
1209    }
1210
1211    /// isKNRPrototype - Return true if this is a K&R style identifier list,
1212    /// like "void foo(a,b,c)".  In a function definition, this will be followed
1213    /// by the argument type definitions.
1214    bool isKNRPrototype() const {
1215      return !hasPrototype && NumArgs != 0;
1216    }
1217
1218    SourceLocation getLParenLoc() const {
1219      return SourceLocation::getFromRawEncoding(LParenLoc);
1220    }
1221
1222    SourceLocation getEllipsisLoc() const {
1223      return SourceLocation::getFromRawEncoding(EllipsisLoc);
1224    }
1225
1226    SourceLocation getRParenLoc() const {
1227      return SourceLocation::getFromRawEncoding(RParenLoc);
1228    }
1229
1230    SourceLocation getExceptionSpecLoc() const {
1231      return SourceLocation::getFromRawEncoding(ExceptionSpecLoc);
1232    }
1233
1234    /// \brief Retrieve the location of the ref-qualifier, if any.
1235    SourceLocation getRefQualifierLoc() const {
1236      return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1237    }
1238
1239    /// \brief Retrieve the location of the ref-qualifier, if any.
1240    SourceLocation getConstQualifierLoc() const {
1241      return SourceLocation::getFromRawEncoding(ConstQualifierLoc);
1242    }
1243
1244    /// \brief Retrieve the location of the ref-qualifier, if any.
1245    SourceLocation getVolatileQualifierLoc() const {
1246      return SourceLocation::getFromRawEncoding(VolatileQualifierLoc);
1247    }
1248
1249    /// \brief Retrieve the location of the 'mutable' qualifier, if any.
1250    SourceLocation getMutableLoc() const {
1251      return SourceLocation::getFromRawEncoding(MutableLoc);
1252    }
1253
1254    /// \brief Determine whether this function declaration contains a
1255    /// ref-qualifier.
1256    bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1257
1258    /// \brief Determine whether this lambda-declarator contains a 'mutable'
1259    /// qualifier.
1260    bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1261
1262    /// \brief Get the type of exception specification this function has.
1263    ExceptionSpecificationType getExceptionSpecType() const {
1264      return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1265    }
1266
1267    /// \brief Determine whether this function declarator had a
1268    /// trailing-return-type.
1269    bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1270
1271    /// \brief Get the trailing-return-type for this function declarator.
1272    ParsedType getTrailingReturnType() const { return TrailingReturnType; }
1273  };
1274
1275  struct BlockPointerTypeInfo : TypeInfoCommon {
1276    /// For now, sema will catch these as invalid.
1277    /// The type qualifiers: const/volatile/restrict.
1278    unsigned TypeQuals : 3;
1279
1280    void destroy() {
1281    }
1282  };
1283
1284  struct MemberPointerTypeInfo : TypeInfoCommon {
1285    /// The type qualifiers: const/volatile/restrict.
1286    unsigned TypeQuals : 3;
1287    // CXXScopeSpec has a constructor, so it can't be a direct member.
1288    // So we need some pointer-aligned storage and a bit of trickery.
1289    union {
1290      void *Aligner;
1291      char Mem[sizeof(CXXScopeSpec)];
1292    } ScopeMem;
1293    CXXScopeSpec &Scope() {
1294      return *reinterpret_cast<CXXScopeSpec*>(ScopeMem.Mem);
1295    }
1296    const CXXScopeSpec &Scope() const {
1297      return *reinterpret_cast<const CXXScopeSpec*>(ScopeMem.Mem);
1298    }
1299    void destroy() {
1300      Scope().~CXXScopeSpec();
1301    }
1302  };
1303
1304  union {
1305    TypeInfoCommon        Common;
1306    PointerTypeInfo       Ptr;
1307    ReferenceTypeInfo     Ref;
1308    ArrayTypeInfo         Arr;
1309    FunctionTypeInfo      Fun;
1310    BlockPointerTypeInfo  Cls;
1311    MemberPointerTypeInfo Mem;
1312  };
1313
1314  void destroy() {
1315    switch (Kind) {
1316    case DeclaratorChunk::Function:      return Fun.destroy();
1317    case DeclaratorChunk::Pointer:       return Ptr.destroy();
1318    case DeclaratorChunk::BlockPointer:  return Cls.destroy();
1319    case DeclaratorChunk::Reference:     return Ref.destroy();
1320    case DeclaratorChunk::Array:         return Arr.destroy();
1321    case DeclaratorChunk::MemberPointer: return Mem.destroy();
1322    case DeclaratorChunk::Paren:         return;
1323    }
1324  }
1325
1326  /// \brief If there are attributes applied to this declaratorchunk, return
1327  /// them.
1328  const AttributeList *getAttrs() const {
1329    return Common.AttrList;
1330  }
1331
1332  AttributeList *&getAttrListRef() {
1333    return Common.AttrList;
1334  }
1335
1336  /// \brief Return a DeclaratorChunk for a pointer.
1337  static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1338                                    SourceLocation ConstQualLoc,
1339                                    SourceLocation VolatileQualLoc,
1340                                    SourceLocation RestrictQualLoc) {
1341    DeclaratorChunk I;
1342    I.Kind                = Pointer;
1343    I.Loc                 = Loc;
1344    I.Ptr.TypeQuals       = TypeQuals;
1345    I.Ptr.ConstQualLoc    = ConstQualLoc.getRawEncoding();
1346    I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1347    I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1348    I.Ptr.AttrList        = 0;
1349    return I;
1350  }
1351
1352  /// \brief Return a DeclaratorChunk for a reference.
1353  static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1354                                      bool lvalue) {
1355    DeclaratorChunk I;
1356    I.Kind            = Reference;
1357    I.Loc             = Loc;
1358    I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1359    I.Ref.LValueRef   = lvalue;
1360    I.Ref.AttrList    = 0;
1361    return I;
1362  }
1363
1364  /// \brief Return a DeclaratorChunk for an array.
1365  static DeclaratorChunk getArray(unsigned TypeQuals,
1366                                  bool isStatic, bool isStar, Expr *NumElts,
1367                                  SourceLocation LBLoc, SourceLocation RBLoc) {
1368    DeclaratorChunk I;
1369    I.Kind          = Array;
1370    I.Loc           = LBLoc;
1371    I.EndLoc        = RBLoc;
1372    I.Arr.AttrList  = 0;
1373    I.Arr.TypeQuals = TypeQuals;
1374    I.Arr.hasStatic = isStatic;
1375    I.Arr.isStar    = isStar;
1376    I.Arr.NumElts   = NumElts;
1377    return I;
1378  }
1379
1380  /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1381  /// "TheDeclarator" is the declarator that this will be added to.
1382  static DeclaratorChunk getFunction(bool hasProto,
1383                                     bool isAmbiguous,
1384                                     SourceLocation LParenLoc,
1385                                     ParamInfo *ArgInfo, unsigned NumArgs,
1386                                     SourceLocation EllipsisLoc,
1387                                     SourceLocation RParenLoc,
1388                                     unsigned TypeQuals,
1389                                     bool RefQualifierIsLvalueRef,
1390                                     SourceLocation RefQualifierLoc,
1391                                     SourceLocation ConstQualifierLoc,
1392                                     SourceLocation VolatileQualifierLoc,
1393                                     SourceLocation MutableLoc,
1394                                     ExceptionSpecificationType ESpecType,
1395                                     SourceLocation ESpecLoc,
1396                                     ParsedType *Exceptions,
1397                                     SourceRange *ExceptionRanges,
1398                                     unsigned NumExceptions,
1399                                     Expr *NoexceptExpr,
1400                                     SourceLocation LocalRangeBegin,
1401                                     SourceLocation LocalRangeEnd,
1402                                     Declarator &TheDeclarator,
1403                                     TypeResult TrailingReturnType =
1404                                                    TypeResult());
1405
1406  /// \brief Return a DeclaratorChunk for a block.
1407  static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1408                                         SourceLocation Loc) {
1409    DeclaratorChunk I;
1410    I.Kind          = BlockPointer;
1411    I.Loc           = Loc;
1412    I.Cls.TypeQuals = TypeQuals;
1413    I.Cls.AttrList  = 0;
1414    return I;
1415  }
1416
1417  static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1418                                          unsigned TypeQuals,
1419                                          SourceLocation Loc) {
1420    DeclaratorChunk I;
1421    I.Kind          = MemberPointer;
1422    I.Loc           = Loc;
1423    I.Mem.TypeQuals = TypeQuals;
1424    I.Mem.AttrList  = 0;
1425    new (I.Mem.ScopeMem.Mem) CXXScopeSpec(SS);
1426    return I;
1427  }
1428
1429  /// \brief Return a DeclaratorChunk for a paren.
1430  static DeclaratorChunk getParen(SourceLocation LParenLoc,
1431                                  SourceLocation RParenLoc) {
1432    DeclaratorChunk I;
1433    I.Kind          = Paren;
1434    I.Loc           = LParenLoc;
1435    I.EndLoc        = RParenLoc;
1436    I.Common.AttrList = 0;
1437    return I;
1438  }
1439
1440  bool isParen() const {
1441    return Kind == Paren;
1442  }
1443};
1444
1445/// \brief Described the kind of function definition (if any) provided for
1446/// a function.
1447enum FunctionDefinitionKind {
1448  FDK_Declaration,
1449  FDK_Definition,
1450  FDK_Defaulted,
1451  FDK_Deleted
1452};
1453
1454/// \brief Information about one declarator, including the parsed type
1455/// information and the identifier.
1456///
1457/// When the declarator is fully formed, this is turned into the appropriate
1458/// Decl object.
1459///
1460/// Declarators come in two types: normal declarators and abstract declarators.
1461/// Abstract declarators are used when parsing types, and don't have an
1462/// identifier.  Normal declarators do have ID's.
1463///
1464/// Instances of this class should be a transient object that lives on the
1465/// stack, not objects that are allocated in large quantities on the heap.
1466class Declarator {
1467public:
1468  enum TheContext {
1469    FileContext,         // File scope declaration.
1470    PrototypeContext,    // Within a function prototype.
1471    ObjCResultContext,   // An ObjC method result type.
1472    ObjCParameterContext,// An ObjC method parameter type.
1473    KNRTypeListContext,  // K&R type definition list for formals.
1474    TypeNameContext,     // Abstract declarator for types.
1475    MemberContext,       // Struct/Union field.
1476    BlockContext,        // Declaration within a block in a function.
1477    ForContext,          // Declaration within first part of a for loop.
1478    ConditionContext,    // Condition declaration in a C++ if/switch/while/for.
1479    TemplateParamContext,// Within a template parameter list.
1480    CXXNewContext,       // C++ new-expression.
1481    CXXCatchContext,     // C++ catch exception-declaration
1482    ObjCCatchContext,    // Objective-C catch exception-declaration
1483    BlockLiteralContext,  // Block literal declarator.
1484    LambdaExprContext,   // Lambda-expression declarator.
1485    TrailingReturnContext, // C++11 trailing-type-specifier.
1486    TemplateTypeArgContext, // Template type argument.
1487    AliasDeclContext,    // C++11 alias-declaration.
1488    AliasTemplateContext // C++11 alias-declaration template.
1489  };
1490
1491private:
1492  const DeclSpec &DS;
1493  CXXScopeSpec SS;
1494  UnqualifiedId Name;
1495  SourceRange Range;
1496
1497  /// \brief Where we are parsing this declarator.
1498  TheContext Context;
1499
1500  /// DeclTypeInfo - This holds each type that the declarator includes as it is
1501  /// parsed.  This is pushed from the identifier out, which means that element
1502  /// #0 will be the most closely bound to the identifier, and
1503  /// DeclTypeInfo.back() will be the least closely bound.
1504  SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1505
1506  /// InvalidType - Set by Sema::GetTypeForDeclarator().
1507  bool InvalidType : 1;
1508
1509  /// GroupingParens - Set by Parser::ParseParenDeclarator().
1510  bool GroupingParens : 1;
1511
1512  /// FunctionDefinition - Is this Declarator for a function or member
1513  /// definition and, if so, what kind?
1514  ///
1515  /// Actually a FunctionDefinitionKind.
1516  unsigned FunctionDefinition : 2;
1517
1518  /// \brief Is this Declarator a redeclaration?
1519  bool Redeclaration : 1;
1520
1521  /// Attrs - Attributes.
1522  ParsedAttributes Attrs;
1523
1524  /// \brief The asm label, if specified.
1525  Expr *AsmLabel;
1526
1527  /// InlineParams - This is a local array used for the first function decl
1528  /// chunk to avoid going to the heap for the common case when we have one
1529  /// function chunk in the declarator.
1530  DeclaratorChunk::ParamInfo InlineParams[16];
1531  bool InlineParamsUsed;
1532
1533  /// \brief true if the declaration is preceded by \c __extension__.
1534  bool Extension : 1;
1535
1536  /// \brief If this is the second or subsequent declarator in this declaration,
1537  /// the location of the comma before this declarator.
1538  SourceLocation CommaLoc;
1539
1540  /// \brief If provided, the source location of the ellipsis used to describe
1541  /// this declarator as a parameter pack.
1542  SourceLocation EllipsisLoc;
1543
1544  friend struct DeclaratorChunk;
1545
1546public:
1547  Declarator(const DeclSpec &ds, TheContext C)
1548    : DS(ds), Range(ds.getSourceRange()), Context(C),
1549      InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1550      GroupingParens(false), FunctionDefinition(FDK_Declaration),
1551      Redeclaration(false),
1552      Attrs(ds.getAttributePool().getFactory()), AsmLabel(0),
1553      InlineParamsUsed(false), Extension(false) {
1554  }
1555
1556  ~Declarator() {
1557    clear();
1558  }
1559
1560  /// getDeclSpec - Return the declaration-specifier that this declarator was
1561  /// declared with.
1562  const DeclSpec &getDeclSpec() const { return DS; }
1563
1564  /// getMutableDeclSpec - Return a non-const version of the DeclSpec.  This
1565  /// should be used with extreme care: declspecs can often be shared between
1566  /// multiple declarators, so mutating the DeclSpec affects all of the
1567  /// Declarators.  This should only be done when the declspec is known to not
1568  /// be shared or when in error recovery etc.
1569  DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1570
1571  AttributePool &getAttributePool() const {
1572    return Attrs.getPool();
1573  }
1574
1575  /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1576  /// nested-name-specifier) that is part of the declarator-id.
1577  const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1578  CXXScopeSpec &getCXXScopeSpec() { return SS; }
1579
1580  /// \brief Retrieve the name specified by this declarator.
1581  UnqualifiedId &getName() { return Name; }
1582
1583  TheContext getContext() const { return Context; }
1584
1585  bool isPrototypeContext() const {
1586    return (Context == PrototypeContext ||
1587            Context == ObjCParameterContext ||
1588            Context == ObjCResultContext);
1589  }
1590
1591  /// \brief Get the source range that spans this declarator.
1592  const SourceRange &getSourceRange() const LLVM_READONLY { return Range; }
1593  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1594  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1595
1596  void SetSourceRange(SourceRange R) { Range = R; }
1597  /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1598  /// invalid.
1599  void SetRangeBegin(SourceLocation Loc) {
1600    if (!Loc.isInvalid())
1601      Range.setBegin(Loc);
1602  }
1603  /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1604  void SetRangeEnd(SourceLocation Loc) {
1605    if (!Loc.isInvalid())
1606      Range.setEnd(Loc);
1607  }
1608  /// ExtendWithDeclSpec - Extend the declarator source range to include the
1609  /// given declspec, unless its location is invalid. Adopts the range start if
1610  /// the current range start is invalid.
1611  void ExtendWithDeclSpec(const DeclSpec &DS) {
1612    const SourceRange &SR = DS.getSourceRange();
1613    if (Range.getBegin().isInvalid())
1614      Range.setBegin(SR.getBegin());
1615    if (!SR.getEnd().isInvalid())
1616      Range.setEnd(SR.getEnd());
1617  }
1618
1619  /// \brief Reset the contents of this Declarator.
1620  void clear() {
1621    SS.clear();
1622    Name.clear();
1623    Range = DS.getSourceRange();
1624
1625    for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1626      DeclTypeInfo[i].destroy();
1627    DeclTypeInfo.clear();
1628    Attrs.clear();
1629    AsmLabel = 0;
1630    InlineParamsUsed = false;
1631    CommaLoc = SourceLocation();
1632    EllipsisLoc = SourceLocation();
1633  }
1634
1635  /// mayOmitIdentifier - Return true if the identifier is either optional or
1636  /// not allowed.  This is true for typenames, prototypes, and template
1637  /// parameter lists.
1638  bool mayOmitIdentifier() const {
1639    switch (Context) {
1640    case FileContext:
1641    case KNRTypeListContext:
1642    case MemberContext:
1643    case BlockContext:
1644    case ForContext:
1645    case ConditionContext:
1646      return false;
1647
1648    case TypeNameContext:
1649    case AliasDeclContext:
1650    case AliasTemplateContext:
1651    case PrototypeContext:
1652    case ObjCParameterContext:
1653    case ObjCResultContext:
1654    case TemplateParamContext:
1655    case CXXNewContext:
1656    case CXXCatchContext:
1657    case ObjCCatchContext:
1658    case BlockLiteralContext:
1659    case LambdaExprContext:
1660    case TemplateTypeArgContext:
1661    case TrailingReturnContext:
1662      return true;
1663    }
1664    llvm_unreachable("unknown context kind!");
1665  }
1666
1667  /// mayHaveIdentifier - Return true if the identifier is either optional or
1668  /// required.  This is true for normal declarators and prototypes, but not
1669  /// typenames.
1670  bool mayHaveIdentifier() const {
1671    switch (Context) {
1672    case FileContext:
1673    case KNRTypeListContext:
1674    case MemberContext:
1675    case BlockContext:
1676    case ForContext:
1677    case ConditionContext:
1678    case PrototypeContext:
1679    case TemplateParamContext:
1680    case CXXCatchContext:
1681    case ObjCCatchContext:
1682      return true;
1683
1684    case TypeNameContext:
1685    case CXXNewContext:
1686    case AliasDeclContext:
1687    case AliasTemplateContext:
1688    case ObjCParameterContext:
1689    case ObjCResultContext:
1690    case BlockLiteralContext:
1691    case LambdaExprContext:
1692    case TemplateTypeArgContext:
1693    case TrailingReturnContext:
1694      return false;
1695    }
1696    llvm_unreachable("unknown context kind!");
1697  }
1698
1699  /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
1700  /// followed by a C++ direct initializer, e.g. "int x(1);".
1701  bool mayBeFollowedByCXXDirectInit() const {
1702    if (hasGroupingParens()) return false;
1703
1704    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1705      return false;
1706
1707    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
1708        Context != FileContext)
1709      return false;
1710
1711    // Special names can't have direct initializers.
1712    if (Name.getKind() != UnqualifiedId::IK_Identifier)
1713      return false;
1714
1715    switch (Context) {
1716    case FileContext:
1717    case BlockContext:
1718    case ForContext:
1719      return true;
1720
1721    case ConditionContext:
1722      // This may not be followed by a direct initializer, but it can't be a
1723      // function declaration either, and we'd prefer to perform a tentative
1724      // parse in order to produce the right diagnostic.
1725      return true;
1726
1727    case KNRTypeListContext:
1728    case MemberContext:
1729    case PrototypeContext:
1730    case ObjCParameterContext:
1731    case ObjCResultContext:
1732    case TemplateParamContext:
1733    case CXXCatchContext:
1734    case ObjCCatchContext:
1735    case TypeNameContext:
1736    case CXXNewContext:
1737    case AliasDeclContext:
1738    case AliasTemplateContext:
1739    case BlockLiteralContext:
1740    case LambdaExprContext:
1741    case TemplateTypeArgContext:
1742    case TrailingReturnContext:
1743      return false;
1744    }
1745    llvm_unreachable("unknown context kind!");
1746  }
1747
1748  /// isPastIdentifier - Return true if we have parsed beyond the point where
1749  /// the
1750  bool isPastIdentifier() const { return Name.isValid(); }
1751
1752  /// hasName - Whether this declarator has a name, which might be an
1753  /// identifier (accessible via getIdentifier()) or some kind of
1754  /// special C++ name (constructor, destructor, etc.).
1755  bool hasName() const {
1756    return Name.getKind() != UnqualifiedId::IK_Identifier || Name.Identifier;
1757  }
1758
1759  IdentifierInfo *getIdentifier() const {
1760    if (Name.getKind() == UnqualifiedId::IK_Identifier)
1761      return Name.Identifier;
1762
1763    return 0;
1764  }
1765  SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
1766
1767  /// \brief Set the name of this declarator to be the given identifier.
1768  void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
1769    Name.setIdentifier(Id, IdLoc);
1770  }
1771
1772  /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
1773  /// EndLoc, which should be the last token of the chunk.
1774  void AddTypeInfo(const DeclaratorChunk &TI,
1775                   ParsedAttributes &attrs,
1776                   SourceLocation EndLoc) {
1777    DeclTypeInfo.push_back(TI);
1778    DeclTypeInfo.back().getAttrListRef() = attrs.getList();
1779    getAttributePool().takeAllFrom(attrs.getPool());
1780
1781    if (!EndLoc.isInvalid())
1782      SetRangeEnd(EndLoc);
1783  }
1784
1785  /// \brief Add a new innermost chunk to this declarator.
1786  void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
1787    DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
1788  }
1789
1790  /// \brief Return the number of types applied to this declarator.
1791  unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
1792
1793  /// Return the specified TypeInfo from this declarator.  TypeInfo #0 is
1794  /// closest to the identifier.
1795  const DeclaratorChunk &getTypeObject(unsigned i) const {
1796    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1797    return DeclTypeInfo[i];
1798  }
1799  DeclaratorChunk &getTypeObject(unsigned i) {
1800    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1801    return DeclTypeInfo[i];
1802  }
1803
1804  void DropFirstTypeObject() {
1805    assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
1806    DeclTypeInfo.front().destroy();
1807    DeclTypeInfo.erase(DeclTypeInfo.begin());
1808  }
1809
1810  /// Return the innermost (closest to the declarator) chunk of this
1811  /// declarator that is not a parens chunk, or null if there are no
1812  /// non-parens chunks.
1813  const DeclaratorChunk *getInnermostNonParenChunk() const {
1814    for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1815      if (!DeclTypeInfo[i].isParen())
1816        return &DeclTypeInfo[i];
1817    }
1818    return 0;
1819  }
1820
1821  /// Return the outermost (furthest from the declarator) chunk of
1822  /// this declarator that is not a parens chunk, or null if there are
1823  /// no non-parens chunks.
1824  const DeclaratorChunk *getOutermostNonParenChunk() const {
1825    for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
1826      if (!DeclTypeInfo[i-1].isParen())
1827        return &DeclTypeInfo[i-1];
1828    }
1829    return 0;
1830  }
1831
1832  /// isArrayOfUnknownBound - This method returns true if the declarator
1833  /// is a declarator for an array of unknown bound (looking through
1834  /// parentheses).
1835  bool isArrayOfUnknownBound() const {
1836    const DeclaratorChunk *chunk = getInnermostNonParenChunk();
1837    return (chunk && chunk->Kind == DeclaratorChunk::Array &&
1838            !chunk->Arr.NumElts);
1839  }
1840
1841  /// isFunctionDeclarator - This method returns true if the declarator
1842  /// is a function declarator (looking through parentheses).
1843  /// If true is returned, then the reference type parameter idx is
1844  /// assigned with the index of the declaration chunk.
1845  bool isFunctionDeclarator(unsigned& idx) const {
1846    for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1847      switch (DeclTypeInfo[i].Kind) {
1848      case DeclaratorChunk::Function:
1849        idx = i;
1850        return true;
1851      case DeclaratorChunk::Paren:
1852        continue;
1853      case DeclaratorChunk::Pointer:
1854      case DeclaratorChunk::Reference:
1855      case DeclaratorChunk::Array:
1856      case DeclaratorChunk::BlockPointer:
1857      case DeclaratorChunk::MemberPointer:
1858        return false;
1859      }
1860      llvm_unreachable("Invalid type chunk");
1861    }
1862    return false;
1863  }
1864
1865  /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
1866  /// this method returns true if the identifier is a function declarator
1867  /// (looking through parentheses).
1868  bool isFunctionDeclarator() const {
1869    unsigned index;
1870    return isFunctionDeclarator(index);
1871  }
1872
1873  /// getFunctionTypeInfo - Retrieves the function type info object
1874  /// (looking through parentheses).
1875  DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
1876    assert(isFunctionDeclarator() && "Not a function declarator!");
1877    unsigned index = 0;
1878    isFunctionDeclarator(index);
1879    return DeclTypeInfo[index].Fun;
1880  }
1881
1882  /// getFunctionTypeInfo - Retrieves the function type info object
1883  /// (looking through parentheses).
1884  const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
1885    return const_cast<Declarator*>(this)->getFunctionTypeInfo();
1886  }
1887
1888  /// \brief Determine whether the declaration that will be produced from
1889  /// this declaration will be a function.
1890  ///
1891  /// A declaration can declare a function even if the declarator itself
1892  /// isn't a function declarator, if the type specifier refers to a function
1893  /// type. This routine checks for both cases.
1894  bool isDeclarationOfFunction() const;
1895
1896  /// \brief Return true if this declaration appears in a context where a
1897  /// function declarator would be a function declaration.
1898  bool isFunctionDeclarationContext() const {
1899    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1900      return false;
1901
1902    switch (Context) {
1903    case FileContext:
1904    case MemberContext:
1905    case BlockContext:
1906      return true;
1907
1908    case ForContext:
1909    case ConditionContext:
1910    case KNRTypeListContext:
1911    case TypeNameContext:
1912    case AliasDeclContext:
1913    case AliasTemplateContext:
1914    case PrototypeContext:
1915    case ObjCParameterContext:
1916    case ObjCResultContext:
1917    case TemplateParamContext:
1918    case CXXNewContext:
1919    case CXXCatchContext:
1920    case ObjCCatchContext:
1921    case BlockLiteralContext:
1922    case LambdaExprContext:
1923    case TemplateTypeArgContext:
1924    case TrailingReturnContext:
1925      return false;
1926    }
1927    llvm_unreachable("unknown context kind!");
1928  }
1929
1930  /// \brief Return true if a function declarator at this position would be a
1931  /// function declaration.
1932  bool isFunctionDeclaratorAFunctionDeclaration() const {
1933    if (!isFunctionDeclarationContext())
1934      return false;
1935
1936    for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
1937      if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
1938        return false;
1939
1940    return true;
1941  }
1942
1943  /// takeAttributes - Takes attributes from the given parsed-attributes
1944  /// set and add them to this declarator.
1945  ///
1946  /// These examples both add 3 attributes to "var":
1947  ///  short int var __attribute__((aligned(16),common,deprecated));
1948  ///  short int x, __attribute__((aligned(16)) var
1949  ///                                 __attribute__((common,deprecated));
1950  ///
1951  /// Also extends the range of the declarator.
1952  void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
1953    Attrs.takeAllFrom(attrs);
1954
1955    if (!lastLoc.isInvalid())
1956      SetRangeEnd(lastLoc);
1957  }
1958
1959  const AttributeList *getAttributes() const { return Attrs.getList(); }
1960  AttributeList *getAttributes() { return Attrs.getList(); }
1961
1962  AttributeList *&getAttrListRef() { return Attrs.getListRef(); }
1963
1964  /// hasAttributes - do we contain any attributes?
1965  bool hasAttributes() const {
1966    if (getAttributes() || getDeclSpec().hasAttributes()) return true;
1967    for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
1968      if (getTypeObject(i).getAttrs())
1969        return true;
1970    return false;
1971  }
1972
1973  /// \brief Return a source range list of C++11 attributes associated
1974  /// with the declarator.
1975  void getCXX11AttributeRanges(SmallVector<SourceRange, 4> &Ranges) {
1976    AttributeList *AttrList = Attrs.getList();
1977    while (AttrList) {
1978      if (AttrList->isCXX11Attribute())
1979        Ranges.push_back(AttrList->getRange());
1980      AttrList = AttrList->getNext();
1981    }
1982  }
1983
1984  void setAsmLabel(Expr *E) { AsmLabel = E; }
1985  Expr *getAsmLabel() const { return AsmLabel; }
1986
1987  void setExtension(bool Val = true) { Extension = Val; }
1988  bool getExtension() const { return Extension; }
1989
1990  void setInvalidType(bool Val = true) { InvalidType = Val; }
1991  bool isInvalidType() const {
1992    return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
1993  }
1994
1995  void setGroupingParens(bool flag) { GroupingParens = flag; }
1996  bool hasGroupingParens() const { return GroupingParens; }
1997
1998  bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
1999  SourceLocation getCommaLoc() const { return CommaLoc; }
2000  void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2001
2002  bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2003  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2004  void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2005
2006  void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2007    FunctionDefinition = Val;
2008  }
2009
2010  bool isFunctionDefinition() const {
2011    return getFunctionDefinitionKind() != FDK_Declaration;
2012  }
2013
2014  FunctionDefinitionKind getFunctionDefinitionKind() const {
2015    return (FunctionDefinitionKind)FunctionDefinition;
2016  }
2017
2018  void setRedeclaration(bool Val) { Redeclaration = Val; }
2019  bool isRedeclaration() const { return Redeclaration; }
2020};
2021
2022/// \brief This little struct is used to capture information about
2023/// structure field declarators, which is basically just a bitfield size.
2024struct FieldDeclarator {
2025  Declarator D;
2026  Expr *BitfieldSize;
2027  explicit FieldDeclarator(const DeclSpec &DS)
2028    : D(DS, Declarator::MemberContext), BitfieldSize(0) { }
2029};
2030
2031/// \brief Represents a C++11 virt-specifier-seq.
2032class VirtSpecifiers {
2033public:
2034  enum Specifier {
2035    VS_None = 0,
2036    VS_Override = 1,
2037    VS_Final = 2
2038  };
2039
2040  VirtSpecifiers() : Specifiers(0) { }
2041
2042  bool SetSpecifier(Specifier VS, SourceLocation Loc,
2043                    const char *&PrevSpec);
2044
2045  bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2046  SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2047
2048  bool isFinalSpecified() const { return Specifiers & VS_Final; }
2049  SourceLocation getFinalLoc() const { return VS_finalLoc; }
2050
2051  void clear() { Specifiers = 0; }
2052
2053  static const char *getSpecifierName(Specifier VS);
2054
2055  SourceLocation getLastLocation() const { return LastLocation; }
2056
2057private:
2058  unsigned Specifiers;
2059
2060  SourceLocation VS_overrideLoc, VS_finalLoc;
2061  SourceLocation LastLocation;
2062};
2063
2064/// \brief An individual capture in a lambda introducer.
2065struct LambdaCapture {
2066  LambdaCaptureKind Kind;
2067  SourceLocation Loc;
2068  IdentifierInfo* Id;
2069  SourceLocation EllipsisLoc;
2070
2071  LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2072                IdentifierInfo* Id = 0,
2073                SourceLocation EllipsisLoc = SourceLocation())
2074    : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc)
2075  {}
2076};
2077
2078/// \brief Represents a complete lambda introducer.
2079struct LambdaIntroducer {
2080  SourceRange Range;
2081  SourceLocation DefaultLoc;
2082  LambdaCaptureDefault Default;
2083  SmallVector<LambdaCapture, 4> Captures;
2084
2085  LambdaIntroducer()
2086    : Default(LCD_None) {}
2087
2088  /// \brief Append a capture in a lambda introducer.
2089  void addCapture(LambdaCaptureKind Kind,
2090                  SourceLocation Loc,
2091                  IdentifierInfo* Id = 0,
2092                  SourceLocation EllipsisLoc = SourceLocation()) {
2093    Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc));
2094  }
2095
2096};
2097
2098} // end namespace clang
2099
2100#endif
2101