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