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