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