DeclSpec.h revision 7121bdb91b86f6053765bda18dd0a8a118929ace
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    LambdaExprParameterContext, // Lambda-expression parameter declarator.
1506    ConversionIdContext, // C++ conversion-type-id.
1507    TrailingReturnContext, // C++11 trailing-type-specifier.
1508    TemplateTypeArgContext, // Template type argument.
1509    AliasDeclContext,    // C++11 alias-declaration.
1510    AliasTemplateContext // C++11 alias-declaration template.
1511  };
1512
1513private:
1514  const DeclSpec &DS;
1515  CXXScopeSpec SS;
1516  UnqualifiedId Name;
1517  SourceRange Range;
1518
1519  /// \brief Where we are parsing this declarator.
1520  TheContext Context;
1521
1522  /// DeclTypeInfo - This holds each type that the declarator includes as it is
1523  /// parsed.  This is pushed from the identifier out, which means that element
1524  /// #0 will be the most closely bound to the identifier, and
1525  /// DeclTypeInfo.back() will be the least closely bound.
1526  SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1527
1528  /// InvalidType - Set by Sema::GetTypeForDeclarator().
1529  bool InvalidType : 1;
1530
1531  /// GroupingParens - Set by Parser::ParseParenDeclarator().
1532  bool GroupingParens : 1;
1533
1534  /// FunctionDefinition - Is this Declarator for a function or member
1535  /// definition and, if so, what kind?
1536  ///
1537  /// Actually a FunctionDefinitionKind.
1538  unsigned FunctionDefinition : 2;
1539
1540  /// \brief Is this Declarator a redeclaration?
1541  bool Redeclaration : 1;
1542
1543  /// Attrs - Attributes.
1544  ParsedAttributes Attrs;
1545
1546  /// \brief The asm label, if specified.
1547  Expr *AsmLabel;
1548
1549  /// InlineParams - This is a local array used for the first function decl
1550  /// chunk to avoid going to the heap for the common case when we have one
1551  /// function chunk in the declarator.
1552  DeclaratorChunk::ParamInfo InlineParams[16];
1553  bool InlineParamsUsed;
1554
1555  /// \brief true if the declaration is preceded by \c __extension__.
1556  bool Extension : 1;
1557
1558  /// \brief If this is the second or subsequent declarator in this declaration,
1559  /// the location of the comma before this declarator.
1560  SourceLocation CommaLoc;
1561
1562  /// \brief If provided, the source location of the ellipsis used to describe
1563  /// this declarator as a parameter pack.
1564  SourceLocation EllipsisLoc;
1565
1566  friend struct DeclaratorChunk;
1567
1568public:
1569  Declarator(const DeclSpec &ds, TheContext C)
1570    : DS(ds), Range(ds.getSourceRange()), Context(C),
1571      InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1572      GroupingParens(false), FunctionDefinition(FDK_Declaration),
1573      Redeclaration(false),
1574      Attrs(ds.getAttributePool().getFactory()), AsmLabel(0),
1575      InlineParamsUsed(false), Extension(false) {
1576  }
1577
1578  ~Declarator() {
1579    clear();
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            Context == LambdaExprParameterContext);
1611  }
1612
1613  /// \brief Get the source range that spans this declarator.
1614  const SourceRange &getSourceRange() const LLVM_READONLY { return Range; }
1615  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1616  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1617
1618  void SetSourceRange(SourceRange R) { Range = R; }
1619  /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1620  /// invalid.
1621  void SetRangeBegin(SourceLocation Loc) {
1622    if (!Loc.isInvalid())
1623      Range.setBegin(Loc);
1624  }
1625  /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1626  void SetRangeEnd(SourceLocation Loc) {
1627    if (!Loc.isInvalid())
1628      Range.setEnd(Loc);
1629  }
1630  /// ExtendWithDeclSpec - Extend the declarator source range to include the
1631  /// given declspec, unless its location is invalid. Adopts the range start if
1632  /// the current range start is invalid.
1633  void ExtendWithDeclSpec(const DeclSpec &DS) {
1634    const SourceRange &SR = DS.getSourceRange();
1635    if (Range.getBegin().isInvalid())
1636      Range.setBegin(SR.getBegin());
1637    if (!SR.getEnd().isInvalid())
1638      Range.setEnd(SR.getEnd());
1639  }
1640
1641  /// \brief Reset the contents of this Declarator.
1642  void clear() {
1643    SS.clear();
1644    Name.clear();
1645    Range = DS.getSourceRange();
1646
1647    for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1648      DeclTypeInfo[i].destroy();
1649    DeclTypeInfo.clear();
1650    Attrs.clear();
1651    AsmLabel = 0;
1652    InlineParamsUsed = false;
1653    CommaLoc = SourceLocation();
1654    EllipsisLoc = SourceLocation();
1655  }
1656
1657  /// mayOmitIdentifier - Return true if the identifier is either optional or
1658  /// not allowed.  This is true for typenames, prototypes, and template
1659  /// parameter lists.
1660  bool mayOmitIdentifier() const {
1661    switch (Context) {
1662    case FileContext:
1663    case KNRTypeListContext:
1664    case MemberContext:
1665    case BlockContext:
1666    case ForContext:
1667    case ConditionContext:
1668      return false;
1669
1670    case TypeNameContext:
1671    case AliasDeclContext:
1672    case AliasTemplateContext:
1673    case PrototypeContext:
1674    case LambdaExprParameterContext:
1675    case ObjCParameterContext:
1676    case ObjCResultContext:
1677    case TemplateParamContext:
1678    case CXXNewContext:
1679    case CXXCatchContext:
1680    case ObjCCatchContext:
1681    case BlockLiteralContext:
1682    case LambdaExprContext:
1683    case ConversionIdContext:
1684    case TemplateTypeArgContext:
1685    case TrailingReturnContext:
1686      return true;
1687    }
1688    llvm_unreachable("unknown context kind!");
1689  }
1690
1691  /// mayHaveIdentifier - Return true if the identifier is either optional or
1692  /// required.  This is true for normal declarators and prototypes, but not
1693  /// typenames.
1694  bool mayHaveIdentifier() const {
1695    switch (Context) {
1696    case FileContext:
1697    case KNRTypeListContext:
1698    case MemberContext:
1699    case BlockContext:
1700    case ForContext:
1701    case ConditionContext:
1702    case PrototypeContext:
1703    case LambdaExprParameterContext:
1704    case TemplateParamContext:
1705    case CXXCatchContext:
1706    case ObjCCatchContext:
1707      return true;
1708
1709    case TypeNameContext:
1710    case CXXNewContext:
1711    case AliasDeclContext:
1712    case AliasTemplateContext:
1713    case ObjCParameterContext:
1714    case ObjCResultContext:
1715    case BlockLiteralContext:
1716    case LambdaExprContext:
1717    case ConversionIdContext:
1718    case TemplateTypeArgContext:
1719    case TrailingReturnContext:
1720      return false;
1721    }
1722    llvm_unreachable("unknown context kind!");
1723  }
1724
1725  /// diagnoseIdentifier - Return true if the identifier is prohibited and
1726  /// should be diagnosed (because it cannot be anything else).
1727  bool diagnoseIdentifier() const {
1728    switch (Context) {
1729    case FileContext:
1730    case KNRTypeListContext:
1731    case MemberContext:
1732    case BlockContext:
1733    case ForContext:
1734    case ConditionContext:
1735    case PrototypeContext:
1736    case LambdaExprParameterContext:
1737    case TemplateParamContext:
1738    case CXXCatchContext:
1739    case ObjCCatchContext:
1740    case TypeNameContext:
1741    case ConversionIdContext:
1742    case ObjCParameterContext:
1743    case ObjCResultContext:
1744    case BlockLiteralContext:
1745    case CXXNewContext:
1746    case LambdaExprContext:
1747      return false;
1748
1749    case AliasDeclContext:
1750    case AliasTemplateContext:
1751    case TemplateTypeArgContext:
1752    case TrailingReturnContext:
1753      return true;
1754    }
1755    llvm_unreachable("unknown context kind!");
1756  }
1757
1758  /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
1759  /// followed by a C++ direct initializer, e.g. "int x(1);".
1760  bool mayBeFollowedByCXXDirectInit() const {
1761    if (hasGroupingParens()) return false;
1762
1763    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1764      return false;
1765
1766    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
1767        Context != FileContext)
1768      return false;
1769
1770    // Special names can't have direct initializers.
1771    if (Name.getKind() != UnqualifiedId::IK_Identifier)
1772      return false;
1773
1774    switch (Context) {
1775    case FileContext:
1776    case BlockContext:
1777    case ForContext:
1778      return true;
1779
1780    case ConditionContext:
1781      // This may not be followed by a direct initializer, but it can't be a
1782      // function declaration either, and we'd prefer to perform a tentative
1783      // parse in order to produce the right diagnostic.
1784      return true;
1785
1786    case KNRTypeListContext:
1787    case MemberContext:
1788    case PrototypeContext:
1789    case LambdaExprParameterContext:
1790    case ObjCParameterContext:
1791    case ObjCResultContext:
1792    case TemplateParamContext:
1793    case CXXCatchContext:
1794    case ObjCCatchContext:
1795    case TypeNameContext:
1796    case CXXNewContext:
1797    case AliasDeclContext:
1798    case AliasTemplateContext:
1799    case BlockLiteralContext:
1800    case LambdaExprContext:
1801    case ConversionIdContext:
1802    case TemplateTypeArgContext:
1803    case TrailingReturnContext:
1804      return false;
1805    }
1806    llvm_unreachable("unknown context kind!");
1807  }
1808
1809  /// isPastIdentifier - Return true if we have parsed beyond the point where
1810  /// the
1811  bool isPastIdentifier() const { return Name.isValid(); }
1812
1813  /// hasName - Whether this declarator has a name, which might be an
1814  /// identifier (accessible via getIdentifier()) or some kind of
1815  /// special C++ name (constructor, destructor, etc.).
1816  bool hasName() const {
1817    return Name.getKind() != UnqualifiedId::IK_Identifier || Name.Identifier;
1818  }
1819
1820  IdentifierInfo *getIdentifier() const {
1821    if (Name.getKind() == UnqualifiedId::IK_Identifier)
1822      return Name.Identifier;
1823
1824    return 0;
1825  }
1826  SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
1827
1828  /// \brief Set the name of this declarator to be the given identifier.
1829  void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
1830    Name.setIdentifier(Id, IdLoc);
1831  }
1832
1833  /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
1834  /// EndLoc, which should be the last token of the chunk.
1835  void AddTypeInfo(const DeclaratorChunk &TI,
1836                   ParsedAttributes &attrs,
1837                   SourceLocation EndLoc) {
1838    DeclTypeInfo.push_back(TI);
1839    DeclTypeInfo.back().getAttrListRef() = attrs.getList();
1840    getAttributePool().takeAllFrom(attrs.getPool());
1841
1842    if (!EndLoc.isInvalid())
1843      SetRangeEnd(EndLoc);
1844  }
1845
1846  /// \brief Add a new innermost chunk to this declarator.
1847  void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
1848    DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
1849  }
1850
1851  /// \brief Return the number of types applied to this declarator.
1852  unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
1853
1854  /// Return the specified TypeInfo from this declarator.  TypeInfo #0 is
1855  /// closest to the identifier.
1856  const DeclaratorChunk &getTypeObject(unsigned i) const {
1857    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1858    return DeclTypeInfo[i];
1859  }
1860  DeclaratorChunk &getTypeObject(unsigned i) {
1861    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1862    return DeclTypeInfo[i];
1863  }
1864
1865  void DropFirstTypeObject() {
1866    assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
1867    DeclTypeInfo.front().destroy();
1868    DeclTypeInfo.erase(DeclTypeInfo.begin());
1869  }
1870
1871  /// Return the innermost (closest to the declarator) chunk of this
1872  /// declarator that is not a parens chunk, or null if there are no
1873  /// non-parens chunks.
1874  const DeclaratorChunk *getInnermostNonParenChunk() const {
1875    for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1876      if (!DeclTypeInfo[i].isParen())
1877        return &DeclTypeInfo[i];
1878    }
1879    return 0;
1880  }
1881
1882  /// Return the outermost (furthest from the declarator) chunk of
1883  /// this declarator that is not a parens chunk, or null if there are
1884  /// no non-parens chunks.
1885  const DeclaratorChunk *getOutermostNonParenChunk() const {
1886    for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
1887      if (!DeclTypeInfo[i-1].isParen())
1888        return &DeclTypeInfo[i-1];
1889    }
1890    return 0;
1891  }
1892
1893  /// isArrayOfUnknownBound - This method returns true if the declarator
1894  /// is a declarator for an array of unknown bound (looking through
1895  /// parentheses).
1896  bool isArrayOfUnknownBound() const {
1897    const DeclaratorChunk *chunk = getInnermostNonParenChunk();
1898    return (chunk && chunk->Kind == DeclaratorChunk::Array &&
1899            !chunk->Arr.NumElts);
1900  }
1901
1902  /// isFunctionDeclarator - This method returns true if the declarator
1903  /// is a function declarator (looking through parentheses).
1904  /// If true is returned, then the reference type parameter idx is
1905  /// assigned with the index of the declaration chunk.
1906  bool isFunctionDeclarator(unsigned& idx) const {
1907    for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1908      switch (DeclTypeInfo[i].Kind) {
1909      case DeclaratorChunk::Function:
1910        idx = i;
1911        return true;
1912      case DeclaratorChunk::Paren:
1913        continue;
1914      case DeclaratorChunk::Pointer:
1915      case DeclaratorChunk::Reference:
1916      case DeclaratorChunk::Array:
1917      case DeclaratorChunk::BlockPointer:
1918      case DeclaratorChunk::MemberPointer:
1919        return false;
1920      }
1921      llvm_unreachable("Invalid type chunk");
1922    }
1923    return false;
1924  }
1925
1926  /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
1927  /// this method returns true if the identifier is a function declarator
1928  /// (looking through parentheses).
1929  bool isFunctionDeclarator() const {
1930    unsigned index;
1931    return isFunctionDeclarator(index);
1932  }
1933
1934  /// getFunctionTypeInfo - Retrieves the function type info object
1935  /// (looking through parentheses).
1936  DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
1937    assert(isFunctionDeclarator() && "Not a function declarator!");
1938    unsigned index = 0;
1939    isFunctionDeclarator(index);
1940    return DeclTypeInfo[index].Fun;
1941  }
1942
1943  /// getFunctionTypeInfo - Retrieves the function type info object
1944  /// (looking through parentheses).
1945  const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
1946    return const_cast<Declarator*>(this)->getFunctionTypeInfo();
1947  }
1948
1949  /// \brief Determine whether the declaration that will be produced from
1950  /// this declaration will be a function.
1951  ///
1952  /// A declaration can declare a function even if the declarator itself
1953  /// isn't a function declarator, if the type specifier refers to a function
1954  /// type. This routine checks for both cases.
1955  bool isDeclarationOfFunction() const;
1956
1957  /// \brief Return true if this declaration appears in a context where a
1958  /// function declarator would be a function declaration.
1959  bool isFunctionDeclarationContext() const {
1960    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1961      return false;
1962
1963    switch (Context) {
1964    case FileContext:
1965    case MemberContext:
1966    case BlockContext:
1967      return true;
1968
1969    case ForContext:
1970    case ConditionContext:
1971    case KNRTypeListContext:
1972    case TypeNameContext:
1973    case AliasDeclContext:
1974    case AliasTemplateContext:
1975    case PrototypeContext:
1976    case LambdaExprParameterContext:
1977    case ObjCParameterContext:
1978    case ObjCResultContext:
1979    case TemplateParamContext:
1980    case CXXNewContext:
1981    case CXXCatchContext:
1982    case ObjCCatchContext:
1983    case BlockLiteralContext:
1984    case LambdaExprContext:
1985    case ConversionIdContext:
1986    case TemplateTypeArgContext:
1987    case TrailingReturnContext:
1988      return false;
1989    }
1990    llvm_unreachable("unknown context kind!");
1991  }
1992
1993  /// \brief Return true if a function declarator at this position would be a
1994  /// function declaration.
1995  bool isFunctionDeclaratorAFunctionDeclaration() const {
1996    if (!isFunctionDeclarationContext())
1997      return false;
1998
1999    for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2000      if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2001        return false;
2002
2003    return true;
2004  }
2005
2006  /// takeAttributes - Takes attributes from the given parsed-attributes
2007  /// set and add them to this declarator.
2008  ///
2009  /// These examples both add 3 attributes to "var":
2010  ///  short int var __attribute__((aligned(16),common,deprecated));
2011  ///  short int x, __attribute__((aligned(16)) var
2012  ///                                 __attribute__((common,deprecated));
2013  ///
2014  /// Also extends the range of the declarator.
2015  void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2016    Attrs.takeAllFrom(attrs);
2017
2018    if (!lastLoc.isInvalid())
2019      SetRangeEnd(lastLoc);
2020  }
2021
2022  const AttributeList *getAttributes() const { return Attrs.getList(); }
2023  AttributeList *getAttributes() { return Attrs.getList(); }
2024
2025  AttributeList *&getAttrListRef() { return Attrs.getListRef(); }
2026
2027  /// hasAttributes - do we contain any attributes?
2028  bool hasAttributes() const {
2029    if (getAttributes() || getDeclSpec().hasAttributes()) return true;
2030    for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2031      if (getTypeObject(i).getAttrs())
2032        return true;
2033    return false;
2034  }
2035
2036  /// \brief Return a source range list of C++11 attributes associated
2037  /// with the declarator.
2038  void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2039    AttributeList *AttrList = Attrs.getList();
2040    while (AttrList) {
2041      if (AttrList->isCXX11Attribute())
2042        Ranges.push_back(AttrList->getRange());
2043      AttrList = AttrList->getNext();
2044    }
2045  }
2046
2047  void setAsmLabel(Expr *E) { AsmLabel = E; }
2048  Expr *getAsmLabel() const { return AsmLabel; }
2049
2050  void setExtension(bool Val = true) { Extension = Val; }
2051  bool getExtension() const { return Extension; }
2052
2053  void setInvalidType(bool Val = true) { InvalidType = Val; }
2054  bool isInvalidType() const {
2055    return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2056  }
2057
2058  void setGroupingParens(bool flag) { GroupingParens = flag; }
2059  bool hasGroupingParens() const { return GroupingParens; }
2060
2061  bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2062  SourceLocation getCommaLoc() const { return CommaLoc; }
2063  void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2064
2065  bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2066  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2067  void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2068
2069  void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2070    FunctionDefinition = Val;
2071  }
2072
2073  bool isFunctionDefinition() const {
2074    return getFunctionDefinitionKind() != FDK_Declaration;
2075  }
2076
2077  FunctionDefinitionKind getFunctionDefinitionKind() const {
2078    return (FunctionDefinitionKind)FunctionDefinition;
2079  }
2080
2081  /// Returns true if this declares a real member and not a friend.
2082  bool isFirstDeclarationOfMember() {
2083    return getContext() == MemberContext && !getDeclSpec().isFriendSpecified();
2084  }
2085
2086  /// Returns true if this declares a static member.  This cannot be called on a
2087  /// declarator outside of a MemberContext because we won't know until
2088  /// redeclaration time if the decl is static.
2089  bool isStaticMember();
2090
2091  void setRedeclaration(bool Val) { Redeclaration = Val; }
2092  bool isRedeclaration() const { return Redeclaration; }
2093};
2094
2095/// \brief This little struct is used to capture information about
2096/// structure field declarators, which is basically just a bitfield size.
2097struct FieldDeclarator {
2098  Declarator D;
2099  Expr *BitfieldSize;
2100  explicit FieldDeclarator(const DeclSpec &DS)
2101    : D(DS, Declarator::MemberContext), BitfieldSize(0) { }
2102};
2103
2104/// \brief Represents a C++11 virt-specifier-seq.
2105class VirtSpecifiers {
2106public:
2107  enum Specifier {
2108    VS_None = 0,
2109    VS_Override = 1,
2110    VS_Final = 2,
2111    VS_Sealed = 4
2112  };
2113
2114  VirtSpecifiers() : Specifiers(0) { }
2115
2116  bool SetSpecifier(Specifier VS, SourceLocation Loc,
2117                    const char *&PrevSpec);
2118
2119  bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2120  SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2121
2122  bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed); }
2123  bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2124  SourceLocation getFinalLoc() const { return VS_finalLoc; }
2125
2126  void clear() { Specifiers = 0; }
2127
2128  static const char *getSpecifierName(Specifier VS);
2129
2130  SourceLocation getLastLocation() const { return LastLocation; }
2131
2132private:
2133  unsigned Specifiers;
2134
2135  SourceLocation VS_overrideLoc, VS_finalLoc;
2136  SourceLocation LastLocation;
2137};
2138
2139/// \brief An individual capture in a lambda introducer.
2140struct LambdaCapture {
2141  LambdaCaptureKind Kind;
2142  SourceLocation Loc;
2143  IdentifierInfo *Id;
2144  SourceLocation EllipsisLoc;
2145  ExprResult Init;
2146
2147  LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2148                IdentifierInfo* Id = 0,
2149                SourceLocation EllipsisLoc = SourceLocation(),
2150                ExprResult Init = ExprResult())
2151    : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc), Init(Init)
2152  {}
2153};
2154
2155/// \brief Represents a complete lambda introducer.
2156struct LambdaIntroducer {
2157  SourceRange Range;
2158  SourceLocation DefaultLoc;
2159  LambdaCaptureDefault Default;
2160  SmallVector<LambdaCapture, 4> Captures;
2161
2162  LambdaIntroducer()
2163    : Default(LCD_None) {}
2164
2165  /// \brief Append a capture in a lambda introducer.
2166  void addCapture(LambdaCaptureKind Kind,
2167                  SourceLocation Loc,
2168                  IdentifierInfo* Id = 0,
2169                  SourceLocation EllipsisLoc = SourceLocation(),
2170                  ExprResult Init = ExprResult()) {
2171    Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, Init));
2172  }
2173};
2174
2175} // end namespace clang
2176
2177#endif
2178