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