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