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