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