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