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 CXXRecordDecl;
41  class TypeLoc;
42  class LangOptions;
43  class IdentifierInfo;
44  class NamespaceAliasDecl;
45  class NamespaceDecl;
46  class ObjCDeclSpec;
47  class Sema;
48  class Declarator;
49  struct TemplateIdAnnotation;
50
51/// \brief Represents a C++ nested-name-specifier or a global scope specifier.
52///
53/// These can be in 3 states:
54///   1) Not present, identified by isEmpty()
55///   2) Present, identified by isNotEmpty()
56///      2.a) Valid, identified by isValid()
57///      2.b) Invalid, identified by isInvalid().
58///
59/// isSet() is deprecated because it mostly corresponded to "valid" but was
60/// often used as if it meant "present".
61///
62/// The actual scope is described by getScopeRep().
63class CXXScopeSpec {
64  SourceRange Range;
65  NestedNameSpecifierLocBuilder Builder;
66
67public:
68  SourceRange getRange() const { return Range; }
69  void setRange(SourceRange R) { Range = R; }
70  void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
71  void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
72  SourceLocation getBeginLoc() const { return Range.getBegin(); }
73  SourceLocation getEndLoc() const { return Range.getEnd(); }
74
75  /// \brief Retrieve the representation of the nested-name-specifier.
76  NestedNameSpecifier *getScopeRep() const {
77    return Builder.getRepresentation();
78  }
79
80  /// \brief Extend the current nested-name-specifier by another
81  /// nested-name-specifier component of the form 'type::'.
82  ///
83  /// \param Context The AST context in which this nested-name-specifier
84  /// resides.
85  ///
86  /// \param TemplateKWLoc The location of the 'template' keyword, if present.
87  ///
88  /// \param TL The TypeLoc that describes the type preceding the '::'.
89  ///
90  /// \param ColonColonLoc The location of the trailing '::'.
91  void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
92              SourceLocation ColonColonLoc);
93
94  /// \brief Extend the current nested-name-specifier by another
95  /// nested-name-specifier component of the form 'identifier::'.
96  ///
97  /// \param Context The AST context in which this nested-name-specifier
98  /// resides.
99  ///
100  /// \param Identifier The identifier.
101  ///
102  /// \param IdentifierLoc The location of the identifier.
103  ///
104  /// \param ColonColonLoc The location of the trailing '::'.
105  void Extend(ASTContext &Context, IdentifierInfo *Identifier,
106              SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
107
108  /// \brief Extend the current nested-name-specifier by another
109  /// nested-name-specifier component of the form 'namespace::'.
110  ///
111  /// \param Context The AST context in which this nested-name-specifier
112  /// resides.
113  ///
114  /// \param Namespace The namespace.
115  ///
116  /// \param NamespaceLoc The location of the namespace name.
117  ///
118  /// \param ColonColonLoc The location of the trailing '::'.
119  void Extend(ASTContext &Context, NamespaceDecl *Namespace,
120              SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
121
122  /// \brief Extend the current nested-name-specifier by another
123  /// nested-name-specifier component of the form 'namespace-alias::'.
124  ///
125  /// \param Context The AST context in which this nested-name-specifier
126  /// resides.
127  ///
128  /// \param Alias The namespace alias.
129  ///
130  /// \param AliasLoc The location of the namespace alias
131  /// name.
132  ///
133  /// \param ColonColonLoc The location of the trailing '::'.
134  void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
135              SourceLocation AliasLoc, SourceLocation ColonColonLoc);
136
137  /// \brief Turn this (empty) nested-name-specifier into the global
138  /// nested-name-specifier '::'.
139  void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
140
141  /// \brief Turns this (empty) nested-name-specifier into '__super'
142  /// nested-name-specifier.
143  ///
144  /// \param Context The AST context in which this nested-name-specifier
145  /// resides.
146  ///
147  /// \param RD The declaration of the class in which nested-name-specifier
148  /// appeared.
149  ///
150  /// \param SuperLoc The location of the '__super' keyword.
151  /// name.
152  ///
153  /// \param ColonColonLoc The location of the trailing '::'.
154  void MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
155                 SourceLocation SuperLoc, SourceLocation ColonColonLoc);
156
157  /// \brief Make a new nested-name-specifier from incomplete source-location
158  /// information.
159  ///
160  /// FIXME: This routine should be used very, very rarely, in cases where we
161  /// need to synthesize a nested-name-specifier. Most code should instead use
162  /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
163  void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
164                   SourceRange R);
165
166  /// \brief Adopt an existing nested-name-specifier (with source-range
167  /// information).
168  void Adopt(NestedNameSpecifierLoc Other);
169
170  /// \brief Retrieve a nested-name-specifier with location information, copied
171  /// into the given AST context.
172  ///
173  /// \param Context The context into which this nested-name-specifier will be
174  /// copied.
175  NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
176
177  /// \brief Retrieve the location of the name in the last qualifier
178  /// in this nested name specifier.
179  ///
180  /// For example, the location of \c bar
181  /// in
182  /// \verbatim
183  ///   \::foo::bar<0>::
184  ///           ^~~
185  /// \endverbatim
186  SourceLocation getLastQualifierNameLoc() const;
187
188  /// No scope specifier.
189  bool isEmpty() const { return !Range.isValid(); }
190  /// A scope specifier is present, but may be valid or invalid.
191  bool isNotEmpty() const { return !isEmpty(); }
192
193  /// An error occurred during parsing of the scope specifier.
194  bool isInvalid() const { return isNotEmpty() && getScopeRep() == nullptr; }
195  /// A scope specifier is present, and it refers to a real scope.
196  bool isValid() const { return isNotEmpty() && getScopeRep() != nullptr; }
197
198  /// \brief Indicate that this nested-name-specifier is invalid.
199  void SetInvalid(SourceRange R) {
200    assert(R.isValid() && "Must have a valid source range");
201    if (Range.getBegin().isInvalid())
202      Range.setBegin(R.getBegin());
203    Range.setEnd(R.getEnd());
204    Builder.Clear();
205  }
206
207  /// Deprecated.  Some call sites intend isNotEmpty() while others intend
208  /// isValid().
209  bool isSet() const { return getScopeRep() != nullptr; }
210
211  void clear() {
212    Range = SourceRange();
213    Builder.Clear();
214  }
215
216  /// \brief Retrieve the data associated with the source-location information.
217  char *location_data() const { return Builder.getBuffer().first; }
218
219  /// \brief Retrieve the size of the data associated with source-location
220  /// information.
221  unsigned location_size() const { return Builder.getBuffer().second; }
222};
223
224/// \brief Captures information about "declaration specifiers".
225///
226/// "Declaration specifiers" encompasses storage-class-specifiers,
227/// type-specifiers, type-qualifiers, and function-specifiers.
228class DeclSpec {
229public:
230  /// \brief storage-class-specifier
231  /// \note The order of these enumerators is important for diagnostics.
232  enum SCS {
233    SCS_unspecified = 0,
234    SCS_typedef,
235    SCS_extern,
236    SCS_static,
237    SCS_auto,
238    SCS_register,
239    SCS_private_extern,
240    SCS_mutable
241  };
242
243  // Import thread storage class specifier enumeration and constants.
244  // These can be combined with SCS_extern and SCS_static.
245  typedef ThreadStorageClassSpecifier TSCS;
246  static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
247  static const TSCS TSCS___thread = clang::TSCS___thread;
248  static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
249  static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
250
251  // Import type specifier width enumeration and constants.
252  typedef TypeSpecifierWidth TSW;
253  static const TSW TSW_unspecified = clang::TSW_unspecified;
254  static const TSW TSW_short = clang::TSW_short;
255  static const TSW TSW_long = clang::TSW_long;
256  static const TSW TSW_longlong = clang::TSW_longlong;
257
258  enum TSC {
259    TSC_unspecified,
260    TSC_imaginary,
261    TSC_complex
262  };
263
264  // Import type specifier sign enumeration and constants.
265  typedef TypeSpecifierSign TSS;
266  static const TSS TSS_unspecified = clang::TSS_unspecified;
267  static const TSS TSS_signed = clang::TSS_signed;
268  static const TSS TSS_unsigned = clang::TSS_unsigned;
269
270  // Import type specifier type enumeration and constants.
271  typedef TypeSpecifierType TST;
272  static const TST TST_unspecified = clang::TST_unspecified;
273  static const TST TST_void = clang::TST_void;
274  static const TST TST_char = clang::TST_char;
275  static const TST TST_wchar = clang::TST_wchar;
276  static const TST TST_char16 = clang::TST_char16;
277  static const TST TST_char32 = clang::TST_char32;
278  static const TST TST_int = clang::TST_int;
279  static const TST TST_int128 = clang::TST_int128;
280  static const TST TST_half = clang::TST_half;
281  static const TST TST_float = clang::TST_float;
282  static const TST TST_double = clang::TST_double;
283  static const TST TST_float128 = clang::TST_float128;
284  static const TST TST_bool = clang::TST_bool;
285  static const TST TST_decimal32 = clang::TST_decimal32;
286  static const TST TST_decimal64 = clang::TST_decimal64;
287  static const TST TST_decimal128 = clang::TST_decimal128;
288  static const TST TST_enum = clang::TST_enum;
289  static const TST TST_union = clang::TST_union;
290  static const TST TST_struct = clang::TST_struct;
291  static const TST TST_interface = clang::TST_interface;
292  static const TST TST_class = clang::TST_class;
293  static const TST TST_typename = clang::TST_typename;
294  static const TST TST_typeofType = clang::TST_typeofType;
295  static const TST TST_typeofExpr = clang::TST_typeofExpr;
296  static const TST TST_decltype = clang::TST_decltype;
297  static const TST TST_decltype_auto = clang::TST_decltype_auto;
298  static const TST TST_underlyingType = clang::TST_underlyingType;
299  static const TST TST_auto = clang::TST_auto;
300  static const TST TST_auto_type = clang::TST_auto_type;
301  static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
302  static const TST TST_atomic = clang::TST_atomic;
303#define GENERIC_IMAGE_TYPE(ImgType, Id) \
304  static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
305#include "clang/Basic/OpenCLImageTypes.def"
306  static const TST TST_error = clang::TST_error;
307
308  // type-qualifiers
309  enum TQ {   // NOTE: These flags must be kept in sync with Qualifiers::TQ.
310    TQ_unspecified = 0,
311    TQ_const       = 1,
312    TQ_restrict    = 2,
313    TQ_volatile    = 4,
314    TQ_unaligned   = 8,
315    // This has no corresponding Qualifiers::TQ value, because it's not treated
316    // as a qualifier in our type system.
317    TQ_atomic      = 16
318  };
319
320  /// ParsedSpecifiers - Flags to query which specifiers were applied.  This is
321  /// returned by getParsedSpecifiers.
322  enum ParsedSpecifiers {
323    PQ_None                  = 0,
324    PQ_StorageClassSpecifier = 1,
325    PQ_TypeSpecifier         = 2,
326    PQ_TypeQualifier         = 4,
327    PQ_FunctionSpecifier     = 8
328  };
329
330private:
331  // storage-class-specifier
332  /*SCS*/unsigned StorageClassSpec : 3;
333  /*TSCS*/unsigned ThreadStorageClassSpec : 2;
334  unsigned SCS_extern_in_linkage_spec : 1;
335
336  // type-specifier
337  /*TSW*/unsigned TypeSpecWidth : 2;
338  /*TSC*/unsigned TypeSpecComplex : 2;
339  /*TSS*/unsigned TypeSpecSign : 2;
340  /*TST*/unsigned TypeSpecType : 6;
341  unsigned TypeAltiVecVector : 1;
342  unsigned TypeAltiVecPixel : 1;
343  unsigned TypeAltiVecBool : 1;
344  unsigned TypeSpecOwned : 1;
345  unsigned TypeSpecPipe : 1;
346
347  // type-qualifiers
348  unsigned TypeQualifiers : 5;  // Bitwise OR of TQ.
349
350  // function-specifier
351  unsigned FS_inline_specified : 1;
352  unsigned FS_forceinline_specified: 1;
353  unsigned FS_virtual_specified : 1;
354  unsigned FS_explicit_specified : 1;
355  unsigned FS_noreturn_specified : 1;
356
357  // friend-specifier
358  unsigned Friend_specified : 1;
359
360  // constexpr-specifier
361  unsigned Constexpr_specified : 1;
362
363  // concept-specifier
364  unsigned Concept_specified : 1;
365
366  union {
367    UnionParsedType TypeRep;
368    Decl *DeclRep;
369    Expr *ExprRep;
370  };
371
372  // attributes.
373  ParsedAttributes Attrs;
374
375  // Scope specifier for the type spec, if applicable.
376  CXXScopeSpec TypeScope;
377
378  // SourceLocation info.  These are null if the item wasn't specified or if
379  // the setting was synthesized.
380  SourceRange Range;
381
382  SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
383  SourceRange TSWRange;
384  SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc;
385  /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
386  /// typename, then this is the location of the named type (if present);
387  /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
388  /// TSTNameLoc provides source range info for tag types.
389  SourceLocation TSTNameLoc;
390  SourceRange TypeofParensRange;
391  SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
392      TQ_unalignedLoc;
393  SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
394  SourceLocation FS_forceinlineLoc;
395  SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc, ConceptLoc;
396  SourceLocation TQ_pipeLoc;
397
398  WrittenBuiltinSpecs writtenBS;
399  void SaveWrittenBuiltinSpecs();
400
401  ObjCDeclSpec *ObjCQualifiers;
402
403  static bool isTypeRep(TST T) {
404    return (T == TST_typename || T == TST_typeofType ||
405            T == TST_underlyingType || T == TST_atomic);
406  }
407  static bool isExprRep(TST T) {
408    return (T == TST_typeofExpr || T == TST_decltype);
409  }
410
411  DeclSpec(const DeclSpec &) = delete;
412  void operator=(const DeclSpec &) = delete;
413public:
414  static bool isDeclRep(TST T) {
415    return (T == TST_enum || T == TST_struct ||
416            T == TST_interface || T == TST_union ||
417            T == TST_class);
418  }
419
420  DeclSpec(AttributeFactory &attrFactory)
421    : StorageClassSpec(SCS_unspecified),
422      ThreadStorageClassSpec(TSCS_unspecified),
423      SCS_extern_in_linkage_spec(false),
424      TypeSpecWidth(TSW_unspecified),
425      TypeSpecComplex(TSC_unspecified),
426      TypeSpecSign(TSS_unspecified),
427      TypeSpecType(TST_unspecified),
428      TypeAltiVecVector(false),
429      TypeAltiVecPixel(false),
430      TypeAltiVecBool(false),
431      TypeSpecOwned(false),
432      TypeSpecPipe(false),
433      TypeQualifiers(TQ_unspecified),
434      FS_inline_specified(false),
435      FS_forceinline_specified(false),
436      FS_virtual_specified(false),
437      FS_explicit_specified(false),
438      FS_noreturn_specified(false),
439      Friend_specified(false),
440      Constexpr_specified(false),
441      Concept_specified(false),
442      Attrs(attrFactory),
443      writtenBS(),
444      ObjCQualifiers(nullptr) {
445  }
446
447  // storage-class-specifier
448  SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
449  TSCS getThreadStorageClassSpec() const {
450    return (TSCS)ThreadStorageClassSpec;
451  }
452  bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
453  void setExternInLinkageSpec(bool Value) {
454    SCS_extern_in_linkage_spec = Value;
455  }
456
457  SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
458  SourceLocation getThreadStorageClassSpecLoc() const {
459    return ThreadStorageClassSpecLoc;
460  }
461
462  void ClearStorageClassSpecs() {
463    StorageClassSpec           = DeclSpec::SCS_unspecified;
464    ThreadStorageClassSpec     = DeclSpec::TSCS_unspecified;
465    SCS_extern_in_linkage_spec = false;
466    StorageClassSpecLoc        = SourceLocation();
467    ThreadStorageClassSpecLoc  = SourceLocation();
468  }
469
470  void ClearTypeSpecType() {
471    TypeSpecType = DeclSpec::TST_unspecified;
472    TypeSpecOwned = false;
473    TSTLoc = SourceLocation();
474  }
475
476  // type-specifier
477  TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
478  TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
479  TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
480  TST getTypeSpecType() const { return (TST)TypeSpecType; }
481  bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
482  bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
483  bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
484  bool isTypeSpecOwned() const { return TypeSpecOwned; }
485  bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
486  bool isTypeSpecPipe() const { return TypeSpecPipe; }
487
488  ParsedType getRepAsType() const {
489    assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
490    return TypeRep;
491  }
492  Decl *getRepAsDecl() const {
493    assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
494    return DeclRep;
495  }
496  Expr *getRepAsExpr() const {
497    assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
498    return ExprRep;
499  }
500  CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
501  const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
502
503  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
504  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
505  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
506
507  SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
508  SourceRange getTypeSpecWidthRange() const { return TSWRange; }
509  SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
510  SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
511  SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
512  SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
513
514  SourceLocation getTypeSpecTypeNameLoc() const {
515    assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename);
516    return TSTNameLoc;
517  }
518
519  SourceRange getTypeofParensRange() const { return TypeofParensRange; }
520  void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
521
522  bool hasAutoTypeSpec() const {
523    return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
524            TypeSpecType == TST_decltype_auto);
525  }
526
527  bool hasTagDefinition() const;
528
529  /// \brief Turn a type-specifier-type into a string like "_Bool" or "union".
530  static const char *getSpecifierName(DeclSpec::TST T,
531                                      const PrintingPolicy &Policy);
532  static const char *getSpecifierName(DeclSpec::TQ Q);
533  static const char *getSpecifierName(DeclSpec::TSS S);
534  static const char *getSpecifierName(DeclSpec::TSC C);
535  static const char *getSpecifierName(DeclSpec::TSW W);
536  static const char *getSpecifierName(DeclSpec::SCS S);
537  static const char *getSpecifierName(DeclSpec::TSCS S);
538
539  // type-qualifiers
540
541  /// getTypeQualifiers - Return a set of TQs.
542  unsigned getTypeQualifiers() const { return TypeQualifiers; }
543  SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
544  SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
545  SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
546  SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
547  SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
548  SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
549
550  /// \brief Clear out all of the type qualifiers.
551  void ClearTypeQualifiers() {
552    TypeQualifiers = 0;
553    TQ_constLoc = SourceLocation();
554    TQ_restrictLoc = SourceLocation();
555    TQ_volatileLoc = SourceLocation();
556    TQ_atomicLoc = SourceLocation();
557    TQ_unalignedLoc = SourceLocation();
558    TQ_pipeLoc = SourceLocation();
559  }
560
561  // function-specifier
562  bool isInlineSpecified() const {
563    return FS_inline_specified | FS_forceinline_specified;
564  }
565  SourceLocation getInlineSpecLoc() const {
566    return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
567  }
568
569  bool isVirtualSpecified() const { return FS_virtual_specified; }
570  SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
571
572  bool isExplicitSpecified() const { return FS_explicit_specified; }
573  SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
574
575  bool isNoreturnSpecified() const { return FS_noreturn_specified; }
576  SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
577
578  void ClearFunctionSpecs() {
579    FS_inline_specified = false;
580    FS_inlineLoc = SourceLocation();
581    FS_forceinline_specified = false;
582    FS_forceinlineLoc = SourceLocation();
583    FS_virtual_specified = false;
584    FS_virtualLoc = SourceLocation();
585    FS_explicit_specified = false;
586    FS_explicitLoc = SourceLocation();
587    FS_noreturn_specified = false;
588    FS_noreturnLoc = SourceLocation();
589  }
590
591  /// \brief Return true if any type-specifier has been found.
592  bool hasTypeSpecifier() const {
593    return getTypeSpecType() != DeclSpec::TST_unspecified ||
594           getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
595           getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
596           getTypeSpecSign() != DeclSpec::TSS_unspecified;
597  }
598
599  /// \brief Return a bitmask of which flavors of specifiers this
600  /// DeclSpec includes.
601  unsigned getParsedSpecifiers() const;
602
603  /// isEmpty - Return true if this declaration specifier is completely empty:
604  /// no tokens were parsed in the production of it.
605  bool isEmpty() const {
606    return getParsedSpecifiers() == DeclSpec::PQ_None;
607  }
608
609  void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
610  void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
611
612  /// These methods set the specified attribute of the DeclSpec and
613  /// return false if there was no error.  If an error occurs (for
614  /// example, if we tried to set "auto" on a spec with "extern"
615  /// already set), they return true and set PrevSpec and DiagID
616  /// such that
617  ///   Diag(Loc, DiagID) << PrevSpec;
618  /// will yield a useful result.
619  ///
620  /// TODO: use a more general approach that still allows these
621  /// diagnostics to be ignored when desired.
622  bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
623                           const char *&PrevSpec, unsigned &DiagID,
624                           const PrintingPolicy &Policy);
625  bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
626                                 const char *&PrevSpec, unsigned &DiagID);
627  bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
628                        unsigned &DiagID, const PrintingPolicy &Policy);
629  bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
630                          unsigned &DiagID);
631  bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
632                       unsigned &DiagID);
633  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
634                       unsigned &DiagID, const PrintingPolicy &Policy);
635  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
636                       unsigned &DiagID, ParsedType Rep,
637                       const PrintingPolicy &Policy);
638  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
639                       unsigned &DiagID, Decl *Rep, bool Owned,
640                       const PrintingPolicy &Policy);
641  bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
642                       SourceLocation TagNameLoc, const char *&PrevSpec,
643                       unsigned &DiagID, ParsedType Rep,
644                       const PrintingPolicy &Policy);
645  bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
646                       SourceLocation TagNameLoc, const char *&PrevSpec,
647                       unsigned &DiagID, Decl *Rep, bool Owned,
648                       const PrintingPolicy &Policy);
649
650  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
651                       unsigned &DiagID, Expr *Rep,
652                       const PrintingPolicy &policy);
653  bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
654                       const char *&PrevSpec, unsigned &DiagID,
655                       const PrintingPolicy &Policy);
656  bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
657                       const char *&PrevSpec, unsigned &DiagID,
658                       const PrintingPolicy &Policy);
659  bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
660                       const char *&PrevSpec, unsigned &DiagID,
661                       const PrintingPolicy &Policy);
662  bool SetTypePipe(bool isPipe, SourceLocation Loc,
663                       const char *&PrevSpec, unsigned &DiagID,
664                       const PrintingPolicy &Policy);
665  bool SetTypeSpecError();
666  void UpdateDeclRep(Decl *Rep) {
667    assert(isDeclRep((TST) TypeSpecType));
668    DeclRep = Rep;
669  }
670  void UpdateTypeRep(ParsedType Rep) {
671    assert(isTypeRep((TST) TypeSpecType));
672    TypeRep = Rep;
673  }
674  void UpdateExprRep(Expr *Rep) {
675    assert(isExprRep((TST) TypeSpecType));
676    ExprRep = Rep;
677  }
678
679  bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
680                   unsigned &DiagID, const LangOptions &Lang);
681
682  bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
683                             unsigned &DiagID);
684  bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
685                                  unsigned &DiagID);
686  bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
687                              unsigned &DiagID);
688  bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
689                               unsigned &DiagID);
690  bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
691                               unsigned &DiagID);
692
693  bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
694                     unsigned &DiagID);
695  bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
696                            unsigned &DiagID);
697  bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
698                        unsigned &DiagID);
699  bool SetConceptSpec(SourceLocation Loc, const char *&PrevSpec,
700                      unsigned &DiagID);
701
702  bool isFriendSpecified() const { return Friend_specified; }
703  SourceLocation getFriendSpecLoc() const { return FriendLoc; }
704
705  bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
706  SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
707
708  bool isConstexprSpecified() const { return Constexpr_specified; }
709  SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
710
711  bool isConceptSpecified() const { return Concept_specified; }
712  SourceLocation getConceptSpecLoc() const { return ConceptLoc; }
713
714  void ClearConstexprSpec() {
715    Constexpr_specified = false;
716    ConstexprLoc = SourceLocation();
717  }
718
719  void ClearConceptSpec() {
720    Concept_specified = false;
721    ConceptLoc = SourceLocation();
722  }
723
724  AttributePool &getAttributePool() const {
725    return Attrs.getPool();
726  }
727
728  /// \brief Concatenates two attribute lists.
729  ///
730  /// The GCC attribute syntax allows for the following:
731  ///
732  /// \code
733  /// short __attribute__(( unused, deprecated ))
734  /// int __attribute__(( may_alias, aligned(16) )) var;
735  /// \endcode
736  ///
737  /// This declares 4 attributes using 2 lists. The following syntax is
738  /// also allowed and equivalent to the previous declaration.
739  ///
740  /// \code
741  /// short __attribute__((unused)) __attribute__((deprecated))
742  /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
743  /// \endcode
744  ///
745  void addAttributes(AttributeList *AL) {
746    Attrs.addAll(AL);
747  }
748
749  bool hasAttributes() const { return !Attrs.empty(); }
750
751  ParsedAttributes &getAttributes() { return Attrs; }
752  const ParsedAttributes &getAttributes() const { return Attrs; }
753
754  void takeAttributesFrom(ParsedAttributes &attrs) {
755    Attrs.takeAllFrom(attrs);
756  }
757
758  /// Finish - This does final analysis of the declspec, issuing diagnostics for
759  /// things like "_Imaginary" (lacking an FP type).  After calling this method,
760  /// DeclSpec is guaranteed self-consistent, even if an error occurred.
761  void Finish(Sema &S, const PrintingPolicy &Policy);
762
763  const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
764    return writtenBS;
765  }
766
767  ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
768  void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
769
770  /// \brief Checks if this DeclSpec can stand alone, without a Declarator.
771  ///
772  /// Only tag declspecs can stand alone.
773  bool isMissingDeclaratorOk();
774};
775
776/// \brief Captures information about "declaration specifiers" specific to
777/// Objective-C.
778class ObjCDeclSpec {
779public:
780  /// ObjCDeclQualifier - Qualifier used on types in method
781  /// declarations.  Not all combinations are sensible.  Parameters
782  /// can be one of { in, out, inout } with one of { bycopy, byref }.
783  /// Returns can either be { oneway } or not.
784  ///
785  /// This should be kept in sync with Decl::ObjCDeclQualifier.
786  enum ObjCDeclQualifier {
787    DQ_None = 0x0,
788    DQ_In = 0x1,
789    DQ_Inout = 0x2,
790    DQ_Out = 0x4,
791    DQ_Bycopy = 0x8,
792    DQ_Byref = 0x10,
793    DQ_Oneway = 0x20,
794    DQ_CSNullability = 0x40
795  };
796
797  /// PropertyAttributeKind - list of property attributes.
798  /// Keep this list in sync with LLVM's Dwarf.h ApplePropertyAttributes.
799  enum ObjCPropertyAttributeKind {
800    DQ_PR_noattr = 0x0,
801    DQ_PR_readonly = 0x01,
802    DQ_PR_getter = 0x02,
803    DQ_PR_assign = 0x04,
804    DQ_PR_readwrite = 0x08,
805    DQ_PR_retain = 0x10,
806    DQ_PR_copy = 0x20,
807    DQ_PR_nonatomic = 0x40,
808    DQ_PR_setter = 0x80,
809    DQ_PR_atomic = 0x100,
810    DQ_PR_weak =   0x200,
811    DQ_PR_strong = 0x400,
812    DQ_PR_unsafe_unretained = 0x800,
813    DQ_PR_nullability = 0x1000,
814    DQ_PR_null_resettable = 0x2000,
815    DQ_PR_class = 0x4000
816  };
817
818  ObjCDeclSpec()
819    : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
820      Nullability(0), GetterName(nullptr), SetterName(nullptr) { }
821
822  ObjCDeclQualifier getObjCDeclQualifier() const {
823    return (ObjCDeclQualifier)objcDeclQualifier;
824  }
825  void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
826    objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
827  }
828  void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
829    objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
830  }
831
832  ObjCPropertyAttributeKind getPropertyAttributes() const {
833    return ObjCPropertyAttributeKind(PropertyAttributes);
834  }
835  void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
836    PropertyAttributes =
837      (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
838  }
839
840  NullabilityKind getNullability() const {
841    assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
842            (getPropertyAttributes() & DQ_PR_nullability)) &&
843           "Objective-C declspec doesn't have nullability");
844    return static_cast<NullabilityKind>(Nullability);
845  }
846
847  SourceLocation getNullabilityLoc() const {
848    assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
849            (getPropertyAttributes() & DQ_PR_nullability)) &&
850           "Objective-C declspec doesn't have nullability");
851    return NullabilityLoc;
852  }
853
854  void setNullability(SourceLocation loc, NullabilityKind kind) {
855    assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
856            (getPropertyAttributes() & DQ_PR_nullability)) &&
857           "Set the nullability declspec or property attribute first");
858    Nullability = static_cast<unsigned>(kind);
859    NullabilityLoc = loc;
860  }
861
862  const IdentifierInfo *getGetterName() const { return GetterName; }
863  IdentifierInfo *getGetterName() { return GetterName; }
864  SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
865  void setGetterName(IdentifierInfo *name, SourceLocation loc) {
866    GetterName = name;
867    GetterNameLoc = loc;
868  }
869
870  const IdentifierInfo *getSetterName() const { return SetterName; }
871  IdentifierInfo *getSetterName() { return SetterName; }
872  SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
873  void setSetterName(IdentifierInfo *name, SourceLocation loc) {
874    SetterName = name;
875    SetterNameLoc = loc;
876  }
877
878private:
879  // FIXME: These two are unrelated and mutually exclusive. So perhaps
880  // we can put them in a union to reflect their mutual exclusivity
881  // (space saving is negligible).
882  unsigned objcDeclQualifier : 7;
883
884  // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
885  unsigned PropertyAttributes : 15;
886
887  unsigned Nullability : 2;
888
889  SourceLocation NullabilityLoc;
890
891  IdentifierInfo *GetterName;    // getter name or NULL if no getter
892  IdentifierInfo *SetterName;    // setter name or NULL if no setter
893  SourceLocation GetterNameLoc; // location of the getter attribute's value
894  SourceLocation SetterNameLoc; // location of the setter attribute's value
895
896};
897
898/// \brief Represents a C++ unqualified-id that has been parsed.
899class UnqualifiedId {
900private:
901  UnqualifiedId(const UnqualifiedId &Other) = delete;
902  const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
903
904public:
905  /// \brief Describes the kind of unqualified-id parsed.
906  enum IdKind {
907    /// \brief An identifier.
908    IK_Identifier,
909    /// \brief An overloaded operator name, e.g., operator+.
910    IK_OperatorFunctionId,
911    /// \brief A conversion function name, e.g., operator int.
912    IK_ConversionFunctionId,
913    /// \brief A user-defined literal name, e.g., operator "" _i.
914    IK_LiteralOperatorId,
915    /// \brief A constructor name.
916    IK_ConstructorName,
917    /// \brief A constructor named via a template-id.
918    IK_ConstructorTemplateId,
919    /// \brief A destructor name.
920    IK_DestructorName,
921    /// \brief A template-id, e.g., f<int>.
922    IK_TemplateId,
923    /// \brief An implicit 'self' parameter
924    IK_ImplicitSelfParam,
925    /// \brief A deduction-guide name (a template-name)
926    IK_DeductionGuideName
927  } Kind;
928
929  struct OFI {
930    /// \brief The kind of overloaded operator.
931    OverloadedOperatorKind Operator;
932
933    /// \brief The source locations of the individual tokens that name
934    /// the operator, e.g., the "new", "[", and "]" tokens in
935    /// operator new [].
936    ///
937    /// Different operators have different numbers of tokens in their name,
938    /// up to three. Any remaining source locations in this array will be
939    /// set to an invalid value for operators with fewer than three tokens.
940    unsigned SymbolLocations[3];
941  };
942
943  /// \brief Anonymous union that holds extra data associated with the
944  /// parsed unqualified-id.
945  union {
946    /// \brief When Kind == IK_Identifier, the parsed identifier, or when
947    /// Kind == IK_UserLiteralId, the identifier suffix.
948    IdentifierInfo *Identifier;
949
950    /// \brief When Kind == IK_OperatorFunctionId, the overloaded operator
951    /// that we parsed.
952    struct OFI OperatorFunctionId;
953
954    /// \brief When Kind == IK_ConversionFunctionId, the type that the
955    /// conversion function names.
956    UnionParsedType ConversionFunctionId;
957
958    /// \brief When Kind == IK_ConstructorName, the class-name of the type
959    /// whose constructor is being referenced.
960    UnionParsedType ConstructorName;
961
962    /// \brief When Kind == IK_DestructorName, the type referred to by the
963    /// class-name.
964    UnionParsedType DestructorName;
965
966    /// \brief When Kind == IK_DeductionGuideName, the parsed template-name.
967    UnionParsedTemplateTy TemplateName;
968
969    /// \brief When Kind == IK_TemplateId or IK_ConstructorTemplateId,
970    /// the template-id annotation that contains the template name and
971    /// template arguments.
972    TemplateIdAnnotation *TemplateId;
973  };
974
975  /// \brief The location of the first token that describes this unqualified-id,
976  /// which will be the location of the identifier, "operator" keyword,
977  /// tilde (for a destructor), or the template name of a template-id.
978  SourceLocation StartLocation;
979
980  /// \brief The location of the last token that describes this unqualified-id.
981  SourceLocation EndLocation;
982
983  UnqualifiedId() : Kind(IK_Identifier), Identifier(nullptr) { }
984
985  /// \brief Clear out this unqualified-id, setting it to default (invalid)
986  /// state.
987  void clear() {
988    Kind = IK_Identifier;
989    Identifier = nullptr;
990    StartLocation = SourceLocation();
991    EndLocation = SourceLocation();
992  }
993
994  /// \brief Determine whether this unqualified-id refers to a valid name.
995  bool isValid() const { return StartLocation.isValid(); }
996
997  /// \brief Determine whether this unqualified-id refers to an invalid name.
998  bool isInvalid() const { return !isValid(); }
999
1000  /// \brief Determine what kind of name we have.
1001  IdKind getKind() const { return Kind; }
1002  void setKind(IdKind kind) { Kind = kind; }
1003
1004  /// \brief Specify that this unqualified-id was parsed as an identifier.
1005  ///
1006  /// \param Id the parsed identifier.
1007  /// \param IdLoc the location of the parsed identifier.
1008  void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1009    Kind = IK_Identifier;
1010    Identifier = const_cast<IdentifierInfo *>(Id);
1011    StartLocation = EndLocation = IdLoc;
1012  }
1013
1014  /// \brief Specify that this unqualified-id was parsed as an
1015  /// operator-function-id.
1016  ///
1017  /// \param OperatorLoc the location of the 'operator' keyword.
1018  ///
1019  /// \param Op the overloaded operator.
1020  ///
1021  /// \param SymbolLocations the locations of the individual operator symbols
1022  /// in the operator.
1023  void setOperatorFunctionId(SourceLocation OperatorLoc,
1024                             OverloadedOperatorKind Op,
1025                             SourceLocation SymbolLocations[3]);
1026
1027  /// \brief Specify that this unqualified-id was parsed as a
1028  /// conversion-function-id.
1029  ///
1030  /// \param OperatorLoc the location of the 'operator' keyword.
1031  ///
1032  /// \param Ty the type to which this conversion function is converting.
1033  ///
1034  /// \param EndLoc the location of the last token that makes up the type name.
1035  void setConversionFunctionId(SourceLocation OperatorLoc,
1036                               ParsedType Ty,
1037                               SourceLocation EndLoc) {
1038    Kind = IK_ConversionFunctionId;
1039    StartLocation = OperatorLoc;
1040    EndLocation = EndLoc;
1041    ConversionFunctionId = Ty;
1042  }
1043
1044  /// \brief Specific that this unqualified-id was parsed as a
1045  /// literal-operator-id.
1046  ///
1047  /// \param Id the parsed identifier.
1048  ///
1049  /// \param OpLoc the location of the 'operator' keyword.
1050  ///
1051  /// \param IdLoc the location of the identifier.
1052  void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1053                              SourceLocation IdLoc) {
1054    Kind = IK_LiteralOperatorId;
1055    Identifier = const_cast<IdentifierInfo *>(Id);
1056    StartLocation = OpLoc;
1057    EndLocation = IdLoc;
1058  }
1059
1060  /// \brief Specify that this unqualified-id was parsed as a constructor name.
1061  ///
1062  /// \param ClassType the class type referred to by the constructor name.
1063  ///
1064  /// \param ClassNameLoc the location of the class name.
1065  ///
1066  /// \param EndLoc the location of the last token that makes up the type name.
1067  void setConstructorName(ParsedType ClassType,
1068                          SourceLocation ClassNameLoc,
1069                          SourceLocation EndLoc) {
1070    Kind = IK_ConstructorName;
1071    StartLocation = ClassNameLoc;
1072    EndLocation = EndLoc;
1073    ConstructorName = ClassType;
1074  }
1075
1076  /// \brief Specify that this unqualified-id was parsed as a
1077  /// template-id that names a constructor.
1078  ///
1079  /// \param TemplateId the template-id annotation that describes the parsed
1080  /// template-id. This UnqualifiedId instance will take ownership of the
1081  /// \p TemplateId and will free it on destruction.
1082  void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1083
1084  /// \brief Specify that this unqualified-id was parsed as a destructor name.
1085  ///
1086  /// \param TildeLoc the location of the '~' that introduces the destructor
1087  /// name.
1088  ///
1089  /// \param ClassType the name of the class referred to by the destructor name.
1090  void setDestructorName(SourceLocation TildeLoc,
1091                         ParsedType ClassType,
1092                         SourceLocation EndLoc) {
1093    Kind = IK_DestructorName;
1094    StartLocation = TildeLoc;
1095    EndLocation = EndLoc;
1096    DestructorName = ClassType;
1097  }
1098
1099  /// \brief Specify that this unqualified-id was parsed as a template-id.
1100  ///
1101  /// \param TemplateId the template-id annotation that describes the parsed
1102  /// template-id. This UnqualifiedId instance will take ownership of the
1103  /// \p TemplateId and will free it on destruction.
1104  void setTemplateId(TemplateIdAnnotation *TemplateId);
1105
1106  /// \brief Specify that this unqualified-id was parsed as a template-name for
1107  /// a deduction-guide.
1108  ///
1109  /// \param Template The parsed template-name.
1110  /// \param TemplateLoc The location of the parsed template-name.
1111  void setDeductionGuideName(ParsedTemplateTy Template,
1112                             SourceLocation TemplateLoc) {
1113    Kind = IK_DeductionGuideName;
1114    TemplateName = Template;
1115    StartLocation = EndLocation = TemplateLoc;
1116  }
1117
1118  /// \brief Return the source range that covers this unqualified-id.
1119  SourceRange getSourceRange() const LLVM_READONLY {
1120    return SourceRange(StartLocation, EndLocation);
1121  }
1122  SourceLocation getLocStart() const LLVM_READONLY { return StartLocation; }
1123  SourceLocation getLocEnd() const LLVM_READONLY { return EndLocation; }
1124};
1125
1126/// \brief A set of tokens that has been cached for later parsing.
1127typedef SmallVector<Token, 4> CachedTokens;
1128
1129/// \brief One instance of this struct is used for each type in a
1130/// declarator that is parsed.
1131///
1132/// This is intended to be a small value object.
1133struct DeclaratorChunk {
1134  enum {
1135    Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1136  } Kind;
1137
1138  /// Loc - The place where this type was defined.
1139  SourceLocation Loc;
1140  /// EndLoc - If valid, the place where this chunck ends.
1141  SourceLocation EndLoc;
1142
1143  SourceRange getSourceRange() const {
1144    if (EndLoc.isInvalid())
1145      return SourceRange(Loc, Loc);
1146    return SourceRange(Loc, EndLoc);
1147  }
1148
1149  struct TypeInfoCommon {
1150    AttributeList *AttrList;
1151  };
1152
1153  struct PointerTypeInfo : TypeInfoCommon {
1154    /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1155    unsigned TypeQuals : 5;
1156
1157    /// The location of the const-qualifier, if any.
1158    unsigned ConstQualLoc;
1159
1160    /// The location of the volatile-qualifier, if any.
1161    unsigned VolatileQualLoc;
1162
1163    /// The location of the restrict-qualifier, if any.
1164    unsigned RestrictQualLoc;
1165
1166    /// The location of the _Atomic-qualifier, if any.
1167    unsigned AtomicQualLoc;
1168
1169    /// The location of the __unaligned-qualifier, if any.
1170    unsigned UnalignedQualLoc;
1171
1172    void destroy() {
1173    }
1174  };
1175
1176  struct ReferenceTypeInfo : TypeInfoCommon {
1177    /// The type qualifier: restrict. [GNU] C++ extension
1178    bool HasRestrict : 1;
1179    /// True if this is an lvalue reference, false if it's an rvalue reference.
1180    bool LValueRef : 1;
1181    void destroy() {
1182    }
1183  };
1184
1185  struct ArrayTypeInfo : TypeInfoCommon {
1186    /// The type qualifiers for the array:
1187    /// const/volatile/restrict/__unaligned/_Atomic.
1188    unsigned TypeQuals : 5;
1189
1190    /// True if this dimension included the 'static' keyword.
1191    unsigned hasStatic : 1;
1192
1193    /// True if this dimension was [*].  In this case, NumElts is null.
1194    unsigned isStar : 1;
1195
1196    /// This is the size of the array, or null if [] or [*] was specified.
1197    /// Since the parser is multi-purpose, and we don't want to impose a root
1198    /// expression class on all clients, NumElts is untyped.
1199    Expr *NumElts;
1200
1201    void destroy() {}
1202  };
1203
1204  /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1205  /// declarator is parsed.  There are two interesting styles of parameters
1206  /// here:
1207  /// K&R-style identifier lists and parameter type lists.  K&R-style identifier
1208  /// lists will have information about the identifier, but no type information.
1209  /// Parameter type lists will have type info (if the actions module provides
1210  /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1211  struct ParamInfo {
1212    IdentifierInfo *Ident;
1213    SourceLocation IdentLoc;
1214    Decl *Param;
1215
1216    /// DefaultArgTokens - When the parameter's default argument
1217    /// cannot be parsed immediately (because it occurs within the
1218    /// declaration of a member function), it will be stored here as a
1219    /// sequence of tokens to be parsed once the class definition is
1220    /// complete. Non-NULL indicates that there is a default argument.
1221    std::unique_ptr<CachedTokens> DefaultArgTokens;
1222
1223    ParamInfo() = default;
1224    ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1225              Decl *param,
1226              std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1227      : Ident(ident), IdentLoc(iloc), Param(param),
1228        DefaultArgTokens(std::move(DefArgTokens)) {}
1229  };
1230
1231  struct TypeAndRange {
1232    ParsedType Ty;
1233    SourceRange Range;
1234  };
1235
1236  struct FunctionTypeInfo : TypeInfoCommon {
1237    /// hasPrototype - This is true if the function had at least one typed
1238    /// parameter.  If the function is () or (a,b,c), then it has no prototype,
1239    /// and is treated as a K&R-style function.
1240    unsigned hasPrototype : 1;
1241
1242    /// isVariadic - If this function has a prototype, and if that
1243    /// proto ends with ',...)', this is true. When true, EllipsisLoc
1244    /// contains the location of the ellipsis.
1245    unsigned isVariadic : 1;
1246
1247    /// Can this declaration be a constructor-style initializer?
1248    unsigned isAmbiguous : 1;
1249
1250    /// \brief Whether the ref-qualifier (if any) is an lvalue reference.
1251    /// Otherwise, it's an rvalue reference.
1252    unsigned RefQualifierIsLValueRef : 1;
1253
1254    /// The type qualifiers: const/volatile/restrict/__unaligned
1255    /// The qualifier bitmask values are the same as in QualType.
1256    unsigned TypeQuals : 4;
1257
1258    /// ExceptionSpecType - An ExceptionSpecificationType value.
1259    unsigned ExceptionSpecType : 4;
1260
1261    /// DeleteParams - If this is true, we need to delete[] Params.
1262    unsigned DeleteParams : 1;
1263
1264    /// HasTrailingReturnType - If this is true, a trailing return type was
1265    /// specified.
1266    unsigned HasTrailingReturnType : 1;
1267
1268    /// The location of the left parenthesis in the source.
1269    unsigned LParenLoc;
1270
1271    /// When isVariadic is true, the location of the ellipsis in the source.
1272    unsigned EllipsisLoc;
1273
1274    /// The location of the right parenthesis in the source.
1275    unsigned RParenLoc;
1276
1277    /// NumParams - This is the number of formal parameters specified by the
1278    /// declarator.
1279    unsigned NumParams;
1280
1281    /// NumExceptionsOrDecls - This is the number of types in the
1282    /// dynamic-exception-decl, if the function has one. In C, this is the
1283    /// number of declarations in the function prototype.
1284    unsigned NumExceptionsOrDecls;
1285
1286    /// \brief The location of the ref-qualifier, if any.
1287    ///
1288    /// If this is an invalid location, there is no ref-qualifier.
1289    unsigned RefQualifierLoc;
1290
1291    /// \brief The location of the const-qualifier, if any.
1292    ///
1293    /// If this is an invalid location, there is no const-qualifier.
1294    unsigned ConstQualifierLoc;
1295
1296    /// \brief The location of the volatile-qualifier, if any.
1297    ///
1298    /// If this is an invalid location, there is no volatile-qualifier.
1299    unsigned VolatileQualifierLoc;
1300
1301    /// \brief The location of the restrict-qualifier, if any.
1302    ///
1303    /// If this is an invalid location, there is no restrict-qualifier.
1304    unsigned RestrictQualifierLoc;
1305
1306    /// \brief The location of the 'mutable' qualifer in a lambda-declarator, if
1307    /// any.
1308    unsigned MutableLoc;
1309
1310    /// \brief The beginning location of the exception specification, if any.
1311    unsigned ExceptionSpecLocBeg;
1312
1313    /// \brief The end location of the exception specification, if any.
1314    unsigned ExceptionSpecLocEnd;
1315
1316    /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1317    /// describe the parameters specified by this function declarator.  null if
1318    /// there are no parameters specified.
1319    ParamInfo *Params;
1320
1321    union {
1322      /// \brief Pointer to a new[]'d array of TypeAndRange objects that
1323      /// contain the types in the function's dynamic exception specification
1324      /// and their locations, if there is one.
1325      TypeAndRange *Exceptions;
1326
1327      /// \brief Pointer to the expression in the noexcept-specifier of this
1328      /// function, if it has one.
1329      Expr *NoexceptExpr;
1330
1331      /// \brief Pointer to the cached tokens for an exception-specification
1332      /// that has not yet been parsed.
1333      CachedTokens *ExceptionSpecTokens;
1334
1335      /// Pointer to a new[]'d array of declarations that need to be available
1336      /// for lookup inside the function body, if one exists. Does not exist in
1337      /// C++.
1338      NamedDecl **DeclsInPrototype;
1339    };
1340
1341    /// \brief If HasTrailingReturnType is true, this is the trailing return
1342    /// type specified.
1343    UnionParsedType TrailingReturnType;
1344
1345    /// \brief Reset the parameter list to having zero parameters.
1346    ///
1347    /// This is used in various places for error recovery.
1348    void freeParams() {
1349      for (unsigned I = 0; I < NumParams; ++I)
1350        Params[I].DefaultArgTokens.reset();
1351      if (DeleteParams) {
1352        delete[] Params;
1353        DeleteParams = false;
1354      }
1355      NumParams = 0;
1356    }
1357
1358    void destroy() {
1359      if (DeleteParams)
1360        delete[] Params;
1361      switch (getExceptionSpecType()) {
1362      default:
1363        break;
1364      case EST_Dynamic:
1365        delete[] Exceptions;
1366        break;
1367      case EST_Unparsed:
1368        delete ExceptionSpecTokens;
1369        break;
1370      case EST_None:
1371        if (NumExceptionsOrDecls != 0)
1372          delete[] DeclsInPrototype;
1373        break;
1374      }
1375    }
1376
1377    /// isKNRPrototype - Return true if this is a K&R style identifier list,
1378    /// like "void foo(a,b,c)".  In a function definition, this will be followed
1379    /// by the parameter type definitions.
1380    bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1381
1382    SourceLocation getLParenLoc() const {
1383      return SourceLocation::getFromRawEncoding(LParenLoc);
1384    }
1385
1386    SourceLocation getEllipsisLoc() const {
1387      return SourceLocation::getFromRawEncoding(EllipsisLoc);
1388    }
1389
1390    SourceLocation getRParenLoc() const {
1391      return SourceLocation::getFromRawEncoding(RParenLoc);
1392    }
1393
1394    SourceLocation getExceptionSpecLocBeg() const {
1395      return SourceLocation::getFromRawEncoding(ExceptionSpecLocBeg);
1396    }
1397
1398    SourceLocation getExceptionSpecLocEnd() const {
1399      return SourceLocation::getFromRawEncoding(ExceptionSpecLocEnd);
1400    }
1401
1402    SourceRange getExceptionSpecRange() const {
1403      return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1404    }
1405
1406    /// \brief Retrieve the location of the ref-qualifier, if any.
1407    SourceLocation getRefQualifierLoc() const {
1408      return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1409    }
1410
1411    /// \brief Retrieve the location of the 'const' qualifier, if any.
1412    SourceLocation getConstQualifierLoc() const {
1413      return SourceLocation::getFromRawEncoding(ConstQualifierLoc);
1414    }
1415
1416    /// \brief Retrieve the location of the 'volatile' qualifier, if any.
1417    SourceLocation getVolatileQualifierLoc() const {
1418      return SourceLocation::getFromRawEncoding(VolatileQualifierLoc);
1419    }
1420
1421    /// \brief Retrieve the location of the 'restrict' qualifier, if any.
1422    SourceLocation getRestrictQualifierLoc() const {
1423      return SourceLocation::getFromRawEncoding(RestrictQualifierLoc);
1424    }
1425
1426    /// \brief Retrieve the location of the 'mutable' qualifier, if any.
1427    SourceLocation getMutableLoc() const {
1428      return SourceLocation::getFromRawEncoding(MutableLoc);
1429    }
1430
1431    /// \brief Determine whether this function declaration contains a
1432    /// ref-qualifier.
1433    bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1434
1435    /// \brief Determine whether this lambda-declarator contains a 'mutable'
1436    /// qualifier.
1437    bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1438
1439    /// \brief Get the type of exception specification this function has.
1440    ExceptionSpecificationType getExceptionSpecType() const {
1441      return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1442    }
1443
1444    /// \brief Get the number of dynamic exception specifications.
1445    unsigned getNumExceptions() const {
1446      assert(ExceptionSpecType != EST_None);
1447      return NumExceptionsOrDecls;
1448    }
1449
1450    /// \brief Get the non-parameter decls defined within this function
1451    /// prototype. Typically these are tag declarations.
1452    ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1453      assert(ExceptionSpecType == EST_None);
1454      return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1455    }
1456
1457    /// \brief Determine whether this function declarator had a
1458    /// trailing-return-type.
1459    bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1460
1461    /// \brief Get the trailing-return-type for this function declarator.
1462    ParsedType getTrailingReturnType() const { return TrailingReturnType; }
1463  };
1464
1465  struct BlockPointerTypeInfo : TypeInfoCommon {
1466    /// For now, sema will catch these as invalid.
1467    /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1468    unsigned TypeQuals : 5;
1469
1470    void destroy() {
1471    }
1472  };
1473
1474  struct MemberPointerTypeInfo : TypeInfoCommon {
1475    /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1476    unsigned TypeQuals : 5;
1477    // CXXScopeSpec has a constructor, so it can't be a direct member.
1478    // So we need some pointer-aligned storage and a bit of trickery.
1479    alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1480    CXXScopeSpec &Scope() {
1481      return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1482    }
1483    const CXXScopeSpec &Scope() const {
1484      return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1485    }
1486    void destroy() {
1487      Scope().~CXXScopeSpec();
1488    }
1489  };
1490
1491  struct PipeTypeInfo : TypeInfoCommon {
1492  /// The access writes.
1493  unsigned AccessWrites : 3;
1494
1495  void destroy() {}
1496  };
1497
1498  union {
1499    TypeInfoCommon        Common;
1500    PointerTypeInfo       Ptr;
1501    ReferenceTypeInfo     Ref;
1502    ArrayTypeInfo         Arr;
1503    FunctionTypeInfo      Fun;
1504    BlockPointerTypeInfo  Cls;
1505    MemberPointerTypeInfo Mem;
1506    PipeTypeInfo          PipeInfo;
1507  };
1508
1509  void destroy() {
1510    switch (Kind) {
1511    case DeclaratorChunk::Function:      return Fun.destroy();
1512    case DeclaratorChunk::Pointer:       return Ptr.destroy();
1513    case DeclaratorChunk::BlockPointer:  return Cls.destroy();
1514    case DeclaratorChunk::Reference:     return Ref.destroy();
1515    case DeclaratorChunk::Array:         return Arr.destroy();
1516    case DeclaratorChunk::MemberPointer: return Mem.destroy();
1517    case DeclaratorChunk::Paren:         return;
1518    case DeclaratorChunk::Pipe:          return PipeInfo.destroy();
1519    }
1520  }
1521
1522  /// \brief If there are attributes applied to this declaratorchunk, return
1523  /// them.
1524  const AttributeList *getAttrs() const {
1525    return Common.AttrList;
1526  }
1527
1528  AttributeList *&getAttrListRef() {
1529    return Common.AttrList;
1530  }
1531
1532  /// \brief Return a DeclaratorChunk for a pointer.
1533  static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1534                                    SourceLocation ConstQualLoc,
1535                                    SourceLocation VolatileQualLoc,
1536                                    SourceLocation RestrictQualLoc,
1537                                    SourceLocation AtomicQualLoc,
1538                                    SourceLocation UnalignedQualLoc) {
1539    DeclaratorChunk I;
1540    I.Kind                = Pointer;
1541    I.Loc                 = Loc;
1542    I.Ptr.TypeQuals       = TypeQuals;
1543    I.Ptr.ConstQualLoc    = ConstQualLoc.getRawEncoding();
1544    I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1545    I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1546    I.Ptr.AtomicQualLoc   = AtomicQualLoc.getRawEncoding();
1547    I.Ptr.UnalignedQualLoc = UnalignedQualLoc.getRawEncoding();
1548    I.Ptr.AttrList        = nullptr;
1549    return I;
1550  }
1551
1552  /// \brief Return a DeclaratorChunk for a reference.
1553  static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1554                                      bool lvalue) {
1555    DeclaratorChunk I;
1556    I.Kind            = Reference;
1557    I.Loc             = Loc;
1558    I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1559    I.Ref.LValueRef   = lvalue;
1560    I.Ref.AttrList    = nullptr;
1561    return I;
1562  }
1563
1564  /// \brief Return a DeclaratorChunk for an array.
1565  static DeclaratorChunk getArray(unsigned TypeQuals,
1566                                  bool isStatic, bool isStar, Expr *NumElts,
1567                                  SourceLocation LBLoc, SourceLocation RBLoc) {
1568    DeclaratorChunk I;
1569    I.Kind          = Array;
1570    I.Loc           = LBLoc;
1571    I.EndLoc        = RBLoc;
1572    I.Arr.AttrList  = nullptr;
1573    I.Arr.TypeQuals = TypeQuals;
1574    I.Arr.hasStatic = isStatic;
1575    I.Arr.isStar    = isStar;
1576    I.Arr.NumElts   = NumElts;
1577    return I;
1578  }
1579
1580  /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1581  /// "TheDeclarator" is the declarator that this will be added to.
1582  static DeclaratorChunk getFunction(bool HasProto,
1583                                     bool IsAmbiguous,
1584                                     SourceLocation LParenLoc,
1585                                     ParamInfo *Params, unsigned NumParams,
1586                                     SourceLocation EllipsisLoc,
1587                                     SourceLocation RParenLoc,
1588                                     unsigned TypeQuals,
1589                                     bool RefQualifierIsLvalueRef,
1590                                     SourceLocation RefQualifierLoc,
1591                                     SourceLocation ConstQualifierLoc,
1592                                     SourceLocation VolatileQualifierLoc,
1593                                     SourceLocation RestrictQualifierLoc,
1594                                     SourceLocation MutableLoc,
1595                                     ExceptionSpecificationType ESpecType,
1596                                     SourceRange ESpecRange,
1597                                     ParsedType *Exceptions,
1598                                     SourceRange *ExceptionRanges,
1599                                     unsigned NumExceptions,
1600                                     Expr *NoexceptExpr,
1601                                     CachedTokens *ExceptionSpecTokens,
1602                                     ArrayRef<NamedDecl *> DeclsInPrototype,
1603                                     SourceLocation LocalRangeBegin,
1604                                     SourceLocation LocalRangeEnd,
1605                                     Declarator &TheDeclarator,
1606                                     TypeResult TrailingReturnType =
1607                                                    TypeResult());
1608
1609  /// \brief Return a DeclaratorChunk for a block.
1610  static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1611                                         SourceLocation Loc) {
1612    DeclaratorChunk I;
1613    I.Kind          = BlockPointer;
1614    I.Loc           = Loc;
1615    I.Cls.TypeQuals = TypeQuals;
1616    I.Cls.AttrList  = nullptr;
1617    return I;
1618  }
1619
1620  /// \brief Return a DeclaratorChunk for a block.
1621  static DeclaratorChunk getPipe(unsigned TypeQuals,
1622                                 SourceLocation Loc) {
1623    DeclaratorChunk I;
1624    I.Kind          = Pipe;
1625    I.Loc           = Loc;
1626    I.Cls.TypeQuals = TypeQuals;
1627    I.Cls.AttrList  = nullptr;
1628    return I;
1629  }
1630
1631  static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1632                                          unsigned TypeQuals,
1633                                          SourceLocation Loc) {
1634    DeclaratorChunk I;
1635    I.Kind          = MemberPointer;
1636    I.Loc           = SS.getBeginLoc();
1637    I.EndLoc        = Loc;
1638    I.Mem.TypeQuals = TypeQuals;
1639    I.Mem.AttrList  = nullptr;
1640    new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1641    return I;
1642  }
1643
1644  /// \brief Return a DeclaratorChunk for a paren.
1645  static DeclaratorChunk getParen(SourceLocation LParenLoc,
1646                                  SourceLocation RParenLoc) {
1647    DeclaratorChunk I;
1648    I.Kind          = Paren;
1649    I.Loc           = LParenLoc;
1650    I.EndLoc        = RParenLoc;
1651    I.Common.AttrList = nullptr;
1652    return I;
1653  }
1654
1655  bool isParen() const {
1656    return Kind == Paren;
1657  }
1658};
1659
1660/// A parsed C++17 decomposition declarator of the form
1661///   '[' identifier-list ']'
1662class DecompositionDeclarator {
1663public:
1664  struct Binding {
1665    IdentifierInfo *Name;
1666    SourceLocation NameLoc;
1667  };
1668
1669private:
1670  /// The locations of the '[' and ']' tokens.
1671  SourceLocation LSquareLoc, RSquareLoc;
1672
1673  /// The bindings.
1674  Binding *Bindings;
1675  unsigned NumBindings : 31;
1676  unsigned DeleteBindings : 1;
1677
1678  friend class Declarator;
1679
1680public:
1681  DecompositionDeclarator()
1682      : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1683  DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1684  DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1685  ~DecompositionDeclarator() {
1686    if (DeleteBindings)
1687      delete[] Bindings;
1688  }
1689
1690  void clear() {
1691    LSquareLoc = RSquareLoc = SourceLocation();
1692    if (DeleteBindings)
1693      delete[] Bindings;
1694    Bindings = nullptr;
1695    NumBindings = 0;
1696    DeleteBindings = false;
1697  }
1698
1699  ArrayRef<Binding> bindings() const {
1700    return llvm::makeArrayRef(Bindings, NumBindings);
1701  }
1702
1703  bool isSet() const { return LSquareLoc.isValid(); }
1704
1705  SourceLocation getLSquareLoc() const { return LSquareLoc; }
1706  SourceLocation getRSquareLoc() const { return RSquareLoc; }
1707  SourceRange getSourceRange() const {
1708    return SourceRange(LSquareLoc, RSquareLoc);
1709  }
1710};
1711
1712/// \brief Described the kind of function definition (if any) provided for
1713/// a function.
1714enum FunctionDefinitionKind {
1715  FDK_Declaration,
1716  FDK_Definition,
1717  FDK_Defaulted,
1718  FDK_Deleted
1719};
1720
1721/// \brief Information about one declarator, including the parsed type
1722/// information and the identifier.
1723///
1724/// When the declarator is fully formed, this is turned into the appropriate
1725/// Decl object.
1726///
1727/// Declarators come in two types: normal declarators and abstract declarators.
1728/// Abstract declarators are used when parsing types, and don't have an
1729/// identifier.  Normal declarators do have ID's.
1730///
1731/// Instances of this class should be a transient object that lives on the
1732/// stack, not objects that are allocated in large quantities on the heap.
1733class Declarator {
1734public:
1735  enum TheContext {
1736    FileContext,         // File scope declaration.
1737    PrototypeContext,    // Within a function prototype.
1738    ObjCResultContext,   // An ObjC method result type.
1739    ObjCParameterContext,// An ObjC method parameter type.
1740    KNRTypeListContext,  // K&R type definition list for formals.
1741    TypeNameContext,     // Abstract declarator for types.
1742    FunctionalCastContext, // Type in a C++ functional cast expression.
1743    MemberContext,       // Struct/Union field.
1744    BlockContext,        // Declaration within a block in a function.
1745    ForContext,          // Declaration within first part of a for loop.
1746    InitStmtContext,     // Declaration within optional init stmt of if/switch.
1747    ConditionContext,    // Condition declaration in a C++ if/switch/while/for.
1748    TemplateParamContext,// Within a template parameter list.
1749    CXXNewContext,       // C++ new-expression.
1750    CXXCatchContext,     // C++ catch exception-declaration
1751    ObjCCatchContext,    // Objective-C catch exception-declaration
1752    BlockLiteralContext, // Block literal declarator.
1753    LambdaExprContext,   // Lambda-expression declarator.
1754    LambdaExprParameterContext, // Lambda-expression parameter declarator.
1755    ConversionIdContext, // C++ conversion-type-id.
1756    TrailingReturnContext, // C++11 trailing-type-specifier.
1757    TemplateTypeArgContext, // Template type argument.
1758    AliasDeclContext,    // C++11 alias-declaration.
1759    AliasTemplateContext // C++11 alias-declaration template.
1760  };
1761
1762private:
1763  const DeclSpec &DS;
1764  CXXScopeSpec SS;
1765  UnqualifiedId Name;
1766  SourceRange Range;
1767
1768  /// \brief Where we are parsing this declarator.
1769  TheContext Context;
1770
1771  /// The C++17 structured binding, if any. This is an alternative to a Name.
1772  DecompositionDeclarator BindingGroup;
1773
1774  /// DeclTypeInfo - This holds each type that the declarator includes as it is
1775  /// parsed.  This is pushed from the identifier out, which means that element
1776  /// #0 will be the most closely bound to the identifier, and
1777  /// DeclTypeInfo.back() will be the least closely bound.
1778  SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1779
1780  /// InvalidType - Set by Sema::GetTypeForDeclarator().
1781  unsigned InvalidType : 1;
1782
1783  /// GroupingParens - Set by Parser::ParseParenDeclarator().
1784  unsigned GroupingParens : 1;
1785
1786  /// FunctionDefinition - Is this Declarator for a function or member
1787  /// definition and, if so, what kind?
1788  ///
1789  /// Actually a FunctionDefinitionKind.
1790  unsigned FunctionDefinition : 2;
1791
1792  /// \brief Is this Declarator a redeclaration?
1793  unsigned Redeclaration : 1;
1794
1795  /// \brief true if the declaration is preceded by \c __extension__.
1796  unsigned Extension : 1;
1797
1798  /// Indicates whether this is an Objective-C instance variable.
1799  unsigned ObjCIvar : 1;
1800
1801  /// Indicates whether this is an Objective-C 'weak' property.
1802  unsigned ObjCWeakProperty : 1;
1803
1804  /// Indicates whether the InlineParams / InlineBindings storage has been used.
1805  unsigned InlineStorageUsed : 1;
1806
1807  /// Attrs - Attributes.
1808  ParsedAttributes Attrs;
1809
1810  /// \brief The asm label, if specified.
1811  Expr *AsmLabel;
1812
1813#ifndef _MSC_VER
1814  union {
1815#endif
1816    /// InlineParams - This is a local array used for the first function decl
1817    /// chunk to avoid going to the heap for the common case when we have one
1818    /// function chunk in the declarator.
1819    DeclaratorChunk::ParamInfo InlineParams[16];
1820    DecompositionDeclarator::Binding InlineBindings[16];
1821#ifndef _MSC_VER
1822  };
1823#endif
1824
1825  /// \brief If this is the second or subsequent declarator in this declaration,
1826  /// the location of the comma before this declarator.
1827  SourceLocation CommaLoc;
1828
1829  /// \brief If provided, the source location of the ellipsis used to describe
1830  /// this declarator as a parameter pack.
1831  SourceLocation EllipsisLoc;
1832
1833  friend struct DeclaratorChunk;
1834
1835public:
1836  Declarator(const DeclSpec &ds, TheContext C)
1837      : DS(ds), Range(ds.getSourceRange()), Context(C),
1838        InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1839        GroupingParens(false), FunctionDefinition(FDK_Declaration),
1840        Redeclaration(false), Extension(false), ObjCIvar(false),
1841        ObjCWeakProperty(false), InlineStorageUsed(false),
1842        Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr) {}
1843
1844  ~Declarator() {
1845    clear();
1846  }
1847  /// getDeclSpec - Return the declaration-specifier that this declarator was
1848  /// declared with.
1849  const DeclSpec &getDeclSpec() const { return DS; }
1850
1851  /// getMutableDeclSpec - Return a non-const version of the DeclSpec.  This
1852  /// should be used with extreme care: declspecs can often be shared between
1853  /// multiple declarators, so mutating the DeclSpec affects all of the
1854  /// Declarators.  This should only be done when the declspec is known to not
1855  /// be shared or when in error recovery etc.
1856  DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1857
1858  AttributePool &getAttributePool() const {
1859    return Attrs.getPool();
1860  }
1861
1862  /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1863  /// nested-name-specifier) that is part of the declarator-id.
1864  const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1865  CXXScopeSpec &getCXXScopeSpec() { return SS; }
1866
1867  /// \brief Retrieve the name specified by this declarator.
1868  UnqualifiedId &getName() { return Name; }
1869
1870  const DecompositionDeclarator &getDecompositionDeclarator() const {
1871    return BindingGroup;
1872  }
1873
1874  TheContext getContext() const { return Context; }
1875
1876  bool isPrototypeContext() const {
1877    return (Context == PrototypeContext ||
1878            Context == ObjCParameterContext ||
1879            Context == ObjCResultContext ||
1880            Context == LambdaExprParameterContext);
1881  }
1882
1883  /// \brief Get the source range that spans this declarator.
1884  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1885  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1886  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1887
1888  void SetSourceRange(SourceRange R) { Range = R; }
1889  /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1890  /// invalid.
1891  void SetRangeBegin(SourceLocation Loc) {
1892    if (!Loc.isInvalid())
1893      Range.setBegin(Loc);
1894  }
1895  /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1896  void SetRangeEnd(SourceLocation Loc) {
1897    if (!Loc.isInvalid())
1898      Range.setEnd(Loc);
1899  }
1900  /// ExtendWithDeclSpec - Extend the declarator source range to include the
1901  /// given declspec, unless its location is invalid. Adopts the range start if
1902  /// the current range start is invalid.
1903  void ExtendWithDeclSpec(const DeclSpec &DS) {
1904    SourceRange SR = DS.getSourceRange();
1905    if (Range.getBegin().isInvalid())
1906      Range.setBegin(SR.getBegin());
1907    if (!SR.getEnd().isInvalid())
1908      Range.setEnd(SR.getEnd());
1909  }
1910
1911  /// \brief Reset the contents of this Declarator.
1912  void clear() {
1913    SS.clear();
1914    Name.clear();
1915    Range = DS.getSourceRange();
1916    BindingGroup.clear();
1917
1918    for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1919      DeclTypeInfo[i].destroy();
1920    DeclTypeInfo.clear();
1921    Attrs.clear();
1922    AsmLabel = nullptr;
1923    InlineStorageUsed = false;
1924    ObjCIvar = false;
1925    ObjCWeakProperty = false;
1926    CommaLoc = SourceLocation();
1927    EllipsisLoc = SourceLocation();
1928  }
1929
1930  /// mayOmitIdentifier - Return true if the identifier is either optional or
1931  /// not allowed.  This is true for typenames, prototypes, and template
1932  /// parameter lists.
1933  bool mayOmitIdentifier() const {
1934    switch (Context) {
1935    case FileContext:
1936    case KNRTypeListContext:
1937    case MemberContext:
1938    case BlockContext:
1939    case ForContext:
1940    case InitStmtContext:
1941    case ConditionContext:
1942      return false;
1943
1944    case TypeNameContext:
1945    case FunctionalCastContext:
1946    case AliasDeclContext:
1947    case AliasTemplateContext:
1948    case PrototypeContext:
1949    case LambdaExprParameterContext:
1950    case ObjCParameterContext:
1951    case ObjCResultContext:
1952    case TemplateParamContext:
1953    case CXXNewContext:
1954    case CXXCatchContext:
1955    case ObjCCatchContext:
1956    case BlockLiteralContext:
1957    case LambdaExprContext:
1958    case ConversionIdContext:
1959    case TemplateTypeArgContext:
1960    case TrailingReturnContext:
1961      return true;
1962    }
1963    llvm_unreachable("unknown context kind!");
1964  }
1965
1966  /// mayHaveIdentifier - Return true if the identifier is either optional or
1967  /// required.  This is true for normal declarators and prototypes, but not
1968  /// typenames.
1969  bool mayHaveIdentifier() const {
1970    switch (Context) {
1971    case FileContext:
1972    case KNRTypeListContext:
1973    case MemberContext:
1974    case BlockContext:
1975    case ForContext:
1976    case InitStmtContext:
1977    case ConditionContext:
1978    case PrototypeContext:
1979    case LambdaExprParameterContext:
1980    case TemplateParamContext:
1981    case CXXCatchContext:
1982    case ObjCCatchContext:
1983      return true;
1984
1985    case TypeNameContext:
1986    case FunctionalCastContext:
1987    case CXXNewContext:
1988    case AliasDeclContext:
1989    case AliasTemplateContext:
1990    case ObjCParameterContext:
1991    case ObjCResultContext:
1992    case BlockLiteralContext:
1993    case LambdaExprContext:
1994    case ConversionIdContext:
1995    case TemplateTypeArgContext:
1996    case TrailingReturnContext:
1997      return false;
1998    }
1999    llvm_unreachable("unknown context kind!");
2000  }
2001
2002  /// Return true if the context permits a C++17 decomposition declarator.
2003  bool mayHaveDecompositionDeclarator() const {
2004    switch (Context) {
2005    case FileContext:
2006      // FIXME: It's not clear that the proposal meant to allow file-scope
2007      // structured bindings, but it does.
2008    case BlockContext:
2009    case ForContext:
2010    case InitStmtContext:
2011      return true;
2012
2013    case ConditionContext:
2014    case MemberContext:
2015    case PrototypeContext:
2016    case TemplateParamContext:
2017      // Maybe one day...
2018      return false;
2019
2020    // These contexts don't allow any kind of non-abstract declarator.
2021    case KNRTypeListContext:
2022    case TypeNameContext:
2023    case FunctionalCastContext:
2024    case AliasDeclContext:
2025    case AliasTemplateContext:
2026    case LambdaExprParameterContext:
2027    case ObjCParameterContext:
2028    case ObjCResultContext:
2029    case CXXNewContext:
2030    case CXXCatchContext:
2031    case ObjCCatchContext:
2032    case BlockLiteralContext:
2033    case LambdaExprContext:
2034    case ConversionIdContext:
2035    case TemplateTypeArgContext:
2036    case TrailingReturnContext:
2037      return false;
2038    }
2039    llvm_unreachable("unknown context kind!");
2040  }
2041
2042  /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2043  /// followed by a C++ direct initializer, e.g. "int x(1);".
2044  bool mayBeFollowedByCXXDirectInit() const {
2045    if (hasGroupingParens()) return false;
2046
2047    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2048      return false;
2049
2050    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2051        Context != FileContext)
2052      return false;
2053
2054    // Special names can't have direct initializers.
2055    if (Name.getKind() != UnqualifiedId::IK_Identifier)
2056      return false;
2057
2058    switch (Context) {
2059    case FileContext:
2060    case BlockContext:
2061    case ForContext:
2062    case InitStmtContext:
2063      return true;
2064
2065    case ConditionContext:
2066      // This may not be followed by a direct initializer, but it can't be a
2067      // function declaration either, and we'd prefer to perform a tentative
2068      // parse in order to produce the right diagnostic.
2069      return true;
2070
2071    case KNRTypeListContext:
2072    case MemberContext:
2073    case PrototypeContext:
2074    case LambdaExprParameterContext:
2075    case ObjCParameterContext:
2076    case ObjCResultContext:
2077    case TemplateParamContext:
2078    case CXXCatchContext:
2079    case ObjCCatchContext:
2080    case TypeNameContext:
2081    case FunctionalCastContext: // FIXME
2082    case CXXNewContext:
2083    case AliasDeclContext:
2084    case AliasTemplateContext:
2085    case BlockLiteralContext:
2086    case LambdaExprContext:
2087    case ConversionIdContext:
2088    case TemplateTypeArgContext:
2089    case TrailingReturnContext:
2090      return false;
2091    }
2092    llvm_unreachable("unknown context kind!");
2093  }
2094
2095  /// isPastIdentifier - Return true if we have parsed beyond the point where
2096  /// the name would appear. (This may happen even if we haven't actually parsed
2097  /// a name, perhaps because this context doesn't require one.)
2098  bool isPastIdentifier() const { return Name.isValid(); }
2099
2100  /// hasName - Whether this declarator has a name, which might be an
2101  /// identifier (accessible via getIdentifier()) or some kind of
2102  /// special C++ name (constructor, destructor, etc.), or a structured
2103  /// binding (which is not exactly a name, but occupies the same position).
2104  bool hasName() const {
2105    return Name.getKind() != UnqualifiedId::IK_Identifier || Name.Identifier ||
2106           isDecompositionDeclarator();
2107  }
2108
2109  /// Return whether this declarator is a decomposition declarator.
2110  bool isDecompositionDeclarator() const {
2111    return BindingGroup.isSet();
2112  }
2113
2114  IdentifierInfo *getIdentifier() const {
2115    if (Name.getKind() == UnqualifiedId::IK_Identifier)
2116      return Name.Identifier;
2117
2118    return nullptr;
2119  }
2120  SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2121
2122  /// \brief Set the name of this declarator to be the given identifier.
2123  void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2124    Name.setIdentifier(Id, IdLoc);
2125  }
2126
2127  /// Set the decomposition bindings for this declarator.
2128  void
2129  setDecompositionBindings(SourceLocation LSquareLoc,
2130                           ArrayRef<DecompositionDeclarator::Binding> Bindings,
2131                           SourceLocation RSquareLoc);
2132
2133  /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2134  /// EndLoc, which should be the last token of the chunk.
2135  void AddTypeInfo(const DeclaratorChunk &TI,
2136                   ParsedAttributes &attrs,
2137                   SourceLocation EndLoc) {
2138    DeclTypeInfo.push_back(TI);
2139    DeclTypeInfo.back().getAttrListRef() = attrs.getList();
2140    getAttributePool().takeAllFrom(attrs.getPool());
2141
2142    if (!EndLoc.isInvalid())
2143      SetRangeEnd(EndLoc);
2144  }
2145
2146  /// \brief Add a new innermost chunk to this declarator.
2147  void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2148    DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2149  }
2150
2151  /// \brief Return the number of types applied to this declarator.
2152  unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2153
2154  /// Return the specified TypeInfo from this declarator.  TypeInfo #0 is
2155  /// closest to the identifier.
2156  const DeclaratorChunk &getTypeObject(unsigned i) const {
2157    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2158    return DeclTypeInfo[i];
2159  }
2160  DeclaratorChunk &getTypeObject(unsigned i) {
2161    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2162    return DeclTypeInfo[i];
2163  }
2164
2165  typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2166  typedef llvm::iterator_range<type_object_iterator> type_object_range;
2167
2168  /// Returns the range of type objects, from the identifier outwards.
2169  type_object_range type_objects() const {
2170    return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2171  }
2172
2173  void DropFirstTypeObject() {
2174    assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
2175    DeclTypeInfo.front().destroy();
2176    DeclTypeInfo.erase(DeclTypeInfo.begin());
2177  }
2178
2179  /// Return the innermost (closest to the declarator) chunk of this
2180  /// declarator that is not a parens chunk, or null if there are no
2181  /// non-parens chunks.
2182  const DeclaratorChunk *getInnermostNonParenChunk() const {
2183    for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2184      if (!DeclTypeInfo[i].isParen())
2185        return &DeclTypeInfo[i];
2186    }
2187    return nullptr;
2188  }
2189
2190  /// Return the outermost (furthest from the declarator) chunk of
2191  /// this declarator that is not a parens chunk, or null if there are
2192  /// no non-parens chunks.
2193  const DeclaratorChunk *getOutermostNonParenChunk() const {
2194    for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2195      if (!DeclTypeInfo[i-1].isParen())
2196        return &DeclTypeInfo[i-1];
2197    }
2198    return nullptr;
2199  }
2200
2201  /// isArrayOfUnknownBound - This method returns true if the declarator
2202  /// is a declarator for an array of unknown bound (looking through
2203  /// parentheses).
2204  bool isArrayOfUnknownBound() const {
2205    const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2206    return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2207            !chunk->Arr.NumElts);
2208  }
2209
2210  /// isFunctionDeclarator - This method returns true if the declarator
2211  /// is a function declarator (looking through parentheses).
2212  /// If true is returned, then the reference type parameter idx is
2213  /// assigned with the index of the declaration chunk.
2214  bool isFunctionDeclarator(unsigned& idx) const {
2215    for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2216      switch (DeclTypeInfo[i].Kind) {
2217      case DeclaratorChunk::Function:
2218        idx = i;
2219        return true;
2220      case DeclaratorChunk::Paren:
2221        continue;
2222      case DeclaratorChunk::Pointer:
2223      case DeclaratorChunk::Reference:
2224      case DeclaratorChunk::Array:
2225      case DeclaratorChunk::BlockPointer:
2226      case DeclaratorChunk::MemberPointer:
2227      case DeclaratorChunk::Pipe:
2228        return false;
2229      }
2230      llvm_unreachable("Invalid type chunk");
2231    }
2232    return false;
2233  }
2234
2235  /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2236  /// this method returns true if the identifier is a function declarator
2237  /// (looking through parentheses).
2238  bool isFunctionDeclarator() const {
2239    unsigned index;
2240    return isFunctionDeclarator(index);
2241  }
2242
2243  /// getFunctionTypeInfo - Retrieves the function type info object
2244  /// (looking through parentheses).
2245  DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2246    assert(isFunctionDeclarator() && "Not a function declarator!");
2247    unsigned index = 0;
2248    isFunctionDeclarator(index);
2249    return DeclTypeInfo[index].Fun;
2250  }
2251
2252  /// getFunctionTypeInfo - Retrieves the function type info object
2253  /// (looking through parentheses).
2254  const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2255    return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2256  }
2257
2258  /// \brief Determine whether the declaration that will be produced from
2259  /// this declaration will be a function.
2260  ///
2261  /// A declaration can declare a function even if the declarator itself
2262  /// isn't a function declarator, if the type specifier refers to a function
2263  /// type. This routine checks for both cases.
2264  bool isDeclarationOfFunction() const;
2265
2266  /// \brief Return true if this declaration appears in a context where a
2267  /// function declarator would be a function declaration.
2268  bool isFunctionDeclarationContext() const {
2269    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2270      return false;
2271
2272    switch (Context) {
2273    case FileContext:
2274    case MemberContext:
2275    case BlockContext:
2276    case ForContext:
2277    case InitStmtContext:
2278      return true;
2279
2280    case ConditionContext:
2281    case KNRTypeListContext:
2282    case TypeNameContext:
2283    case FunctionalCastContext:
2284    case AliasDeclContext:
2285    case AliasTemplateContext:
2286    case PrototypeContext:
2287    case LambdaExprParameterContext:
2288    case ObjCParameterContext:
2289    case ObjCResultContext:
2290    case TemplateParamContext:
2291    case CXXNewContext:
2292    case CXXCatchContext:
2293    case ObjCCatchContext:
2294    case BlockLiteralContext:
2295    case LambdaExprContext:
2296    case ConversionIdContext:
2297    case TemplateTypeArgContext:
2298    case TrailingReturnContext:
2299      return false;
2300    }
2301    llvm_unreachable("unknown context kind!");
2302  }
2303
2304  /// \brief Return true if a function declarator at this position would be a
2305  /// function declaration.
2306  bool isFunctionDeclaratorAFunctionDeclaration() const {
2307    if (!isFunctionDeclarationContext())
2308      return false;
2309
2310    for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2311      if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2312        return false;
2313
2314    return true;
2315  }
2316
2317  /// \brief Determine whether a trailing return type was written (at any
2318  /// level) within this declarator.
2319  bool hasTrailingReturnType() const {
2320    for (const auto &Chunk : type_objects())
2321      if (Chunk.Kind == DeclaratorChunk::Function &&
2322          Chunk.Fun.hasTrailingReturnType())
2323        return true;
2324    return false;
2325  }
2326
2327  /// takeAttributes - Takes attributes from the given parsed-attributes
2328  /// set and add them to this declarator.
2329  ///
2330  /// These examples both add 3 attributes to "var":
2331  ///  short int var __attribute__((aligned(16),common,deprecated));
2332  ///  short int x, __attribute__((aligned(16)) var
2333  ///                                 __attribute__((common,deprecated));
2334  ///
2335  /// Also extends the range of the declarator.
2336  void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2337    Attrs.takeAllFrom(attrs);
2338
2339    if (!lastLoc.isInvalid())
2340      SetRangeEnd(lastLoc);
2341  }
2342
2343  const AttributeList *getAttributes() const { return Attrs.getList(); }
2344  AttributeList *getAttributes() { return Attrs.getList(); }
2345
2346  AttributeList *&getAttrListRef() { return Attrs.getListRef(); }
2347
2348  /// hasAttributes - do we contain any attributes?
2349  bool hasAttributes() const {
2350    if (getAttributes() || getDeclSpec().hasAttributes()) return true;
2351    for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2352      if (getTypeObject(i).getAttrs())
2353        return true;
2354    return false;
2355  }
2356
2357  /// \brief Return a source range list of C++11 attributes associated
2358  /// with the declarator.
2359  void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2360    AttributeList *AttrList = Attrs.getList();
2361    while (AttrList) {
2362      if (AttrList->isCXX11Attribute())
2363        Ranges.push_back(AttrList->getRange());
2364      AttrList = AttrList->getNext();
2365    }
2366  }
2367
2368  void setAsmLabel(Expr *E) { AsmLabel = E; }
2369  Expr *getAsmLabel() const { return AsmLabel; }
2370
2371  void setExtension(bool Val = true) { Extension = Val; }
2372  bool getExtension() const { return Extension; }
2373
2374  void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2375  bool isObjCIvar() const { return ObjCIvar; }
2376
2377  void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2378  bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2379
2380  void setInvalidType(bool Val = true) { InvalidType = Val; }
2381  bool isInvalidType() const {
2382    return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2383  }
2384
2385  void setGroupingParens(bool flag) { GroupingParens = flag; }
2386  bool hasGroupingParens() const { return GroupingParens; }
2387
2388  bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2389  SourceLocation getCommaLoc() const { return CommaLoc; }
2390  void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2391
2392  bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2393  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2394  void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2395
2396  void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2397    FunctionDefinition = Val;
2398  }
2399
2400  bool isFunctionDefinition() const {
2401    return getFunctionDefinitionKind() != FDK_Declaration;
2402  }
2403
2404  FunctionDefinitionKind getFunctionDefinitionKind() const {
2405    return (FunctionDefinitionKind)FunctionDefinition;
2406  }
2407
2408  /// Returns true if this declares a real member and not a friend.
2409  bool isFirstDeclarationOfMember() {
2410    return getContext() == MemberContext && !getDeclSpec().isFriendSpecified();
2411  }
2412
2413  /// Returns true if this declares a static member.  This cannot be called on a
2414  /// declarator outside of a MemberContext because we won't know until
2415  /// redeclaration time if the decl is static.
2416  bool isStaticMember();
2417
2418  /// Returns true if this declares a constructor or a destructor.
2419  bool isCtorOrDtor();
2420
2421  void setRedeclaration(bool Val) { Redeclaration = Val; }
2422  bool isRedeclaration() const { return Redeclaration; }
2423};
2424
2425/// \brief This little struct is used to capture information about
2426/// structure field declarators, which is basically just a bitfield size.
2427struct FieldDeclarator {
2428  Declarator D;
2429  Expr *BitfieldSize;
2430  explicit FieldDeclarator(const DeclSpec &DS)
2431    : D(DS, Declarator::MemberContext), BitfieldSize(nullptr) { }
2432};
2433
2434/// \brief Represents a C++11 virt-specifier-seq.
2435class VirtSpecifiers {
2436public:
2437  enum Specifier {
2438    VS_None = 0,
2439    VS_Override = 1,
2440    VS_Final = 2,
2441    VS_Sealed = 4,
2442    // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2443    VS_GNU_Final = 8
2444  };
2445
2446  VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2447
2448  bool SetSpecifier(Specifier VS, SourceLocation Loc,
2449                    const char *&PrevSpec);
2450
2451  bool isUnset() const { return Specifiers == 0; }
2452
2453  bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2454  SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2455
2456  bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2457  bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2458  SourceLocation getFinalLoc() const { return VS_finalLoc; }
2459
2460  void clear() { Specifiers = 0; }
2461
2462  static const char *getSpecifierName(Specifier VS);
2463
2464  SourceLocation getFirstLocation() const { return FirstLocation; }
2465  SourceLocation getLastLocation() const { return LastLocation; }
2466  Specifier getLastSpecifier() const { return LastSpecifier; }
2467
2468private:
2469  unsigned Specifiers;
2470  Specifier LastSpecifier;
2471
2472  SourceLocation VS_overrideLoc, VS_finalLoc;
2473  SourceLocation FirstLocation;
2474  SourceLocation LastLocation;
2475};
2476
2477enum class LambdaCaptureInitKind {
2478  NoInit,     //!< [a]
2479  CopyInit,   //!< [a = b], [a = {b}]
2480  DirectInit, //!< [a(b)]
2481  ListInit    //!< [a{b}]
2482};
2483
2484/// \brief Represents a complete lambda introducer.
2485struct LambdaIntroducer {
2486  /// \brief An individual capture in a lambda introducer.
2487  struct LambdaCapture {
2488    LambdaCaptureKind Kind;
2489    SourceLocation Loc;
2490    IdentifierInfo *Id;
2491    SourceLocation EllipsisLoc;
2492    LambdaCaptureInitKind InitKind;
2493    ExprResult Init;
2494    ParsedType InitCaptureType;
2495    LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2496                  IdentifierInfo *Id, SourceLocation EllipsisLoc,
2497                  LambdaCaptureInitKind InitKind, ExprResult Init,
2498                  ParsedType InitCaptureType)
2499        : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2500          InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType) {}
2501  };
2502
2503  SourceRange Range;
2504  SourceLocation DefaultLoc;
2505  LambdaCaptureDefault Default;
2506  SmallVector<LambdaCapture, 4> Captures;
2507
2508  LambdaIntroducer()
2509    : Default(LCD_None) {}
2510
2511  /// \brief Append a capture in a lambda introducer.
2512  void addCapture(LambdaCaptureKind Kind,
2513                  SourceLocation Loc,
2514                  IdentifierInfo* Id,
2515                  SourceLocation EllipsisLoc,
2516                  LambdaCaptureInitKind InitKind,
2517                  ExprResult Init,
2518                  ParsedType InitCaptureType) {
2519    Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2520                                     InitCaptureType));
2521  }
2522};
2523
2524} // end namespace clang
2525
2526#endif // LLVM_CLANG_SEMA_DECLSPEC_H
2527