1 //===--- DeclSpec.h - Parsed declaration specifiers -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file defines the classes used to store parsed information about
12 /// declaration-specifiers and declarators.
15 /// static const int volatile x, *y, *(*(*z)[10])(const void *x);
16 /// ------------------------- - -- ---------------------------
17 /// declaration-specifiers \ | /
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_CLANG_SEMA_DECLSPEC_H
24 #define LLVM_CLANG_SEMA_DECLSPEC_H
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"
44 class NamespaceAliasDecl;
49 struct TemplateIdAnnotation;
51 /// \brief Represents a C++ nested-name-specifier or a global scope specifier.
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().
59 /// isSet() is deprecated because it mostly corresponded to "valid" but was
60 /// often used as if it meant "present".
62 /// The actual scope is described by getScopeRep().
65 NestedNameSpecifierLocBuilder Builder;
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(); }
75 /// \brief Retrieve the representation of the nested-name-specifier.
76 NestedNameSpecifier *getScopeRep() const {
77 return Builder.getRepresentation();
80 /// \brief Extend the current nested-name-specifier by another
81 /// nested-name-specifier component of the form 'type::'.
83 /// \param Context The AST context in which this nested-name-specifier
86 /// \param TemplateKWLoc The location of the 'template' keyword, if present.
88 /// \param TL The TypeLoc that describes the type preceding the '::'.
90 /// \param ColonColonLoc The location of the trailing '::'.
91 void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
92 SourceLocation ColonColonLoc);
94 /// \brief Extend the current nested-name-specifier by another
95 /// nested-name-specifier component of the form 'identifier::'.
97 /// \param Context The AST context in which this nested-name-specifier
100 /// \param Identifier The identifier.
102 /// \param IdentifierLoc The location of the identifier.
104 /// \param ColonColonLoc The location of the trailing '::'.
105 void Extend(ASTContext &Context, IdentifierInfo *Identifier,
106 SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
108 /// \brief Extend the current nested-name-specifier by another
109 /// nested-name-specifier component of the form 'namespace::'.
111 /// \param Context The AST context in which this nested-name-specifier
114 /// \param Namespace The namespace.
116 /// \param NamespaceLoc The location of the namespace name.
118 /// \param ColonColonLoc The location of the trailing '::'.
119 void Extend(ASTContext &Context, NamespaceDecl *Namespace,
120 SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
122 /// \brief Extend the current nested-name-specifier by another
123 /// nested-name-specifier component of the form 'namespace-alias::'.
125 /// \param Context The AST context in which this nested-name-specifier
128 /// \param Alias The namespace alias.
130 /// \param AliasLoc The location of the namespace alias
133 /// \param ColonColonLoc The location of the trailing '::'.
134 void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
135 SourceLocation AliasLoc, SourceLocation ColonColonLoc);
137 /// \brief Turn this (empty) nested-name-specifier into the global
138 /// nested-name-specifier '::'.
139 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
141 /// \brief Turns this (empty) nested-name-specifier into '__super'
142 /// nested-name-specifier.
144 /// \param Context The AST context in which this nested-name-specifier
147 /// \param RD The declaration of the class in which nested-name-specifier
150 /// \param SuperLoc The location of the '__super' keyword.
153 /// \param ColonColonLoc The location of the trailing '::'.
154 void MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
155 SourceLocation SuperLoc, SourceLocation ColonColonLoc);
157 /// \brief Make a new nested-name-specifier from incomplete source-location
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,
166 /// \brief Adopt an existing nested-name-specifier (with source-range
168 void Adopt(NestedNameSpecifierLoc Other);
170 /// \brief Retrieve a nested-name-specifier with location information, copied
171 /// into the given AST context.
173 /// \param Context The context into which this nested-name-specifier will be
175 NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
177 /// \brief Retrieve the location of the name in the last qualifier
178 /// in this nested name specifier.
180 /// For example, the location of \c bar
186 SourceLocation getLastQualifierNameLoc() const;
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(); }
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; }
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());
207 /// Deprecated. Some call sites intend isNotEmpty() while others intend
209 bool isSet() const { return getScopeRep() != nullptr; }
212 Range = SourceRange();
216 /// \brief Retrieve the data associated with the source-location information.
217 char *location_data() const { return Builder.getBuffer().first; }
219 /// \brief Retrieve the size of the data associated with source-location
221 unsigned location_size() const { return Builder.getBuffer().second; }
224 /// \brief Captures information about "declaration specifiers".
226 /// "Declaration specifiers" encompasses storage-class-specifiers,
227 /// type-specifiers, type-qualifiers, and function-specifiers.
230 /// \brief storage-class-specifier
231 /// \note The order of these enumerators is important for diagnostics.
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;
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;
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;
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_float16 = clang::TST_Float16;
284 static const TST TST_float128 = clang::TST_float128;
285 static const TST TST_bool = clang::TST_bool;
286 static const TST TST_decimal32 = clang::TST_decimal32;
287 static const TST TST_decimal64 = clang::TST_decimal64;
288 static const TST TST_decimal128 = clang::TST_decimal128;
289 static const TST TST_enum = clang::TST_enum;
290 static const TST TST_union = clang::TST_union;
291 static const TST TST_struct = clang::TST_struct;
292 static const TST TST_interface = clang::TST_interface;
293 static const TST TST_class = clang::TST_class;
294 static const TST TST_typename = clang::TST_typename;
295 static const TST TST_typeofType = clang::TST_typeofType;
296 static const TST TST_typeofExpr = clang::TST_typeofExpr;
297 static const TST TST_decltype = clang::TST_decltype;
298 static const TST TST_decltype_auto = clang::TST_decltype_auto;
299 static const TST TST_underlyingType = clang::TST_underlyingType;
300 static const TST TST_auto = clang::TST_auto;
301 static const TST TST_auto_type = clang::TST_auto_type;
302 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
303 static const TST TST_atomic = clang::TST_atomic;
304 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
305 static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
306 #include "clang/Basic/OpenCLImageTypes.def"
307 static const TST TST_error = clang::TST_error;
310 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
316 // This has no corresponding Qualifiers::TQ value, because it's not treated
317 // as a qualifier in our type system.
321 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
322 /// returned by getParsedSpecifiers.
323 enum ParsedSpecifiers {
325 PQ_StorageClassSpecifier = 1,
326 PQ_TypeSpecifier = 2,
327 PQ_TypeQualifier = 4,
328 PQ_FunctionSpecifier = 8
332 // storage-class-specifier
333 /*SCS*/unsigned StorageClassSpec : 3;
334 /*TSCS*/unsigned ThreadStorageClassSpec : 2;
335 unsigned SCS_extern_in_linkage_spec : 1;
338 /*TSW*/unsigned TypeSpecWidth : 2;
339 /*TSC*/unsigned TypeSpecComplex : 2;
340 /*TSS*/unsigned TypeSpecSign : 2;
341 /*TST*/unsigned TypeSpecType : 6;
342 unsigned TypeAltiVecVector : 1;
343 unsigned TypeAltiVecPixel : 1;
344 unsigned TypeAltiVecBool : 1;
345 unsigned TypeSpecOwned : 1;
346 unsigned TypeSpecPipe : 1;
349 unsigned TypeQualifiers : 5; // Bitwise OR of TQ.
351 // function-specifier
352 unsigned FS_inline_specified : 1;
353 unsigned FS_forceinline_specified: 1;
354 unsigned FS_virtual_specified : 1;
355 unsigned FS_explicit_specified : 1;
356 unsigned FS_noreturn_specified : 1;
359 unsigned Friend_specified : 1;
361 // constexpr-specifier
362 unsigned Constexpr_specified : 1;
365 UnionParsedType TypeRep;
371 ParsedAttributes Attrs;
373 // Scope specifier for the type spec, if applicable.
374 CXXScopeSpec TypeScope;
376 // SourceLocation info. These are null if the item wasn't specified or if
377 // the setting was synthesized.
380 SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
381 SourceRange TSWRange;
382 SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc;
383 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
384 /// typename, then this is the location of the named type (if present);
385 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
386 /// TSTNameLoc provides source range info for tag types.
387 SourceLocation TSTNameLoc;
388 SourceRange TypeofParensRange;
389 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
391 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
392 SourceLocation FS_forceinlineLoc;
393 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
394 SourceLocation TQ_pipeLoc;
396 WrittenBuiltinSpecs writtenBS;
397 void SaveWrittenBuiltinSpecs();
399 ObjCDeclSpec *ObjCQualifiers;
401 static bool isTypeRep(TST T) {
402 return (T == TST_typename || T == TST_typeofType ||
403 T == TST_underlyingType || T == TST_atomic);
405 static bool isExprRep(TST T) {
406 return (T == TST_typeofExpr || T == TST_decltype);
409 DeclSpec(const DeclSpec &) = delete;
410 void operator=(const DeclSpec &) = delete;
412 static bool isDeclRep(TST T) {
413 return (T == TST_enum || T == TST_struct ||
414 T == TST_interface || T == TST_union ||
418 DeclSpec(AttributeFactory &attrFactory)
419 : StorageClassSpec(SCS_unspecified),
420 ThreadStorageClassSpec(TSCS_unspecified),
421 SCS_extern_in_linkage_spec(false),
422 TypeSpecWidth(TSW_unspecified),
423 TypeSpecComplex(TSC_unspecified),
424 TypeSpecSign(TSS_unspecified),
425 TypeSpecType(TST_unspecified),
426 TypeAltiVecVector(false),
427 TypeAltiVecPixel(false),
428 TypeAltiVecBool(false),
429 TypeSpecOwned(false),
431 TypeQualifiers(TQ_unspecified),
432 FS_inline_specified(false),
433 FS_forceinline_specified(false),
434 FS_virtual_specified(false),
435 FS_explicit_specified(false),
436 FS_noreturn_specified(false),
437 Friend_specified(false),
438 Constexpr_specified(false),
441 ObjCQualifiers(nullptr) {
444 // storage-class-specifier
445 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
446 TSCS getThreadStorageClassSpec() const {
447 return (TSCS)ThreadStorageClassSpec;
449 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
450 void setExternInLinkageSpec(bool Value) {
451 SCS_extern_in_linkage_spec = Value;
454 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
455 SourceLocation getThreadStorageClassSpecLoc() const {
456 return ThreadStorageClassSpecLoc;
459 void ClearStorageClassSpecs() {
460 StorageClassSpec = DeclSpec::SCS_unspecified;
461 ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
462 SCS_extern_in_linkage_spec = false;
463 StorageClassSpecLoc = SourceLocation();
464 ThreadStorageClassSpecLoc = SourceLocation();
467 void ClearTypeSpecType() {
468 TypeSpecType = DeclSpec::TST_unspecified;
469 TypeSpecOwned = false;
470 TSTLoc = SourceLocation();
474 TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
475 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
476 TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
477 TST getTypeSpecType() const { return (TST)TypeSpecType; }
478 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
479 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
480 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
481 bool isTypeSpecOwned() const { return TypeSpecOwned; }
482 bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
483 bool isTypeSpecPipe() const { return TypeSpecPipe; }
485 ParsedType getRepAsType() const {
486 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
489 Decl *getRepAsDecl() const {
490 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
493 Expr *getRepAsExpr() const {
494 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
497 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
498 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
500 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
501 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
502 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
504 SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
505 SourceRange getTypeSpecWidthRange() const { return TSWRange; }
506 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
507 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
508 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
509 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
511 SourceLocation getTypeSpecTypeNameLoc() const {
512 assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename);
516 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
517 void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
519 bool hasAutoTypeSpec() const {
520 return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
521 TypeSpecType == TST_decltype_auto);
524 bool hasTagDefinition() const;
526 /// \brief Turn a type-specifier-type into a string like "_Bool" or "union".
527 static const char *getSpecifierName(DeclSpec::TST T,
528 const PrintingPolicy &Policy);
529 static const char *getSpecifierName(DeclSpec::TQ Q);
530 static const char *getSpecifierName(DeclSpec::TSS S);
531 static const char *getSpecifierName(DeclSpec::TSC C);
532 static const char *getSpecifierName(DeclSpec::TSW W);
533 static const char *getSpecifierName(DeclSpec::SCS S);
534 static const char *getSpecifierName(DeclSpec::TSCS S);
538 /// getTypeQualifiers - Return a set of TQs.
539 unsigned getTypeQualifiers() const { return TypeQualifiers; }
540 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
541 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
542 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
543 SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
544 SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
545 SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
547 /// \brief Clear out all of the type qualifiers.
548 void ClearTypeQualifiers() {
550 TQ_constLoc = SourceLocation();
551 TQ_restrictLoc = SourceLocation();
552 TQ_volatileLoc = SourceLocation();
553 TQ_atomicLoc = SourceLocation();
554 TQ_unalignedLoc = SourceLocation();
555 TQ_pipeLoc = SourceLocation();
558 // function-specifier
559 bool isInlineSpecified() const {
560 return FS_inline_specified | FS_forceinline_specified;
562 SourceLocation getInlineSpecLoc() const {
563 return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
566 bool isVirtualSpecified() const { return FS_virtual_specified; }
567 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
569 bool isExplicitSpecified() const { return FS_explicit_specified; }
570 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
572 bool isNoreturnSpecified() const { return FS_noreturn_specified; }
573 SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
575 void ClearFunctionSpecs() {
576 FS_inline_specified = false;
577 FS_inlineLoc = SourceLocation();
578 FS_forceinline_specified = false;
579 FS_forceinlineLoc = SourceLocation();
580 FS_virtual_specified = false;
581 FS_virtualLoc = SourceLocation();
582 FS_explicit_specified = false;
583 FS_explicitLoc = SourceLocation();
584 FS_noreturn_specified = false;
585 FS_noreturnLoc = SourceLocation();
588 /// \brief Return true if any type-specifier has been found.
589 bool hasTypeSpecifier() const {
590 return getTypeSpecType() != DeclSpec::TST_unspecified ||
591 getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
592 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
593 getTypeSpecSign() != DeclSpec::TSS_unspecified;
596 /// \brief Return a bitmask of which flavors of specifiers this
597 /// DeclSpec includes.
598 unsigned getParsedSpecifiers() const;
600 /// isEmpty - Return true if this declaration specifier is completely empty:
601 /// no tokens were parsed in the production of it.
602 bool isEmpty() const {
603 return getParsedSpecifiers() == DeclSpec::PQ_None;
606 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
607 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
609 /// These methods set the specified attribute of the DeclSpec and
610 /// return false if there was no error. If an error occurs (for
611 /// example, if we tried to set "auto" on a spec with "extern"
612 /// already set), they return true and set PrevSpec and DiagID
614 /// Diag(Loc, DiagID) << PrevSpec;
615 /// will yield a useful result.
617 /// TODO: use a more general approach that still allows these
618 /// diagnostics to be ignored when desired.
619 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
620 const char *&PrevSpec, unsigned &DiagID,
621 const PrintingPolicy &Policy);
622 bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
623 const char *&PrevSpec, unsigned &DiagID);
624 bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
625 unsigned &DiagID, const PrintingPolicy &Policy);
626 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
628 bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
630 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
631 unsigned &DiagID, const PrintingPolicy &Policy);
632 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
633 unsigned &DiagID, ParsedType Rep,
634 const PrintingPolicy &Policy);
635 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
636 unsigned &DiagID, Decl *Rep, bool Owned,
637 const PrintingPolicy &Policy);
638 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
639 SourceLocation TagNameLoc, const char *&PrevSpec,
640 unsigned &DiagID, ParsedType Rep,
641 const PrintingPolicy &Policy);
642 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
643 SourceLocation TagNameLoc, const char *&PrevSpec,
644 unsigned &DiagID, Decl *Rep, bool Owned,
645 const PrintingPolicy &Policy);
647 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
648 unsigned &DiagID, Expr *Rep,
649 const PrintingPolicy &policy);
650 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
651 const char *&PrevSpec, unsigned &DiagID,
652 const PrintingPolicy &Policy);
653 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
654 const char *&PrevSpec, unsigned &DiagID,
655 const PrintingPolicy &Policy);
656 bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
657 const char *&PrevSpec, unsigned &DiagID,
658 const PrintingPolicy &Policy);
659 bool SetTypePipe(bool isPipe, SourceLocation Loc,
660 const char *&PrevSpec, unsigned &DiagID,
661 const PrintingPolicy &Policy);
662 bool SetTypeSpecError();
663 void UpdateDeclRep(Decl *Rep) {
664 assert(isDeclRep((TST) TypeSpecType));
667 void UpdateTypeRep(ParsedType Rep) {
668 assert(isTypeRep((TST) TypeSpecType));
671 void UpdateExprRep(Expr *Rep) {
672 assert(isExprRep((TST) TypeSpecType));
676 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
677 unsigned &DiagID, const LangOptions &Lang);
679 bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
681 bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
683 bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
685 bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
687 bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
690 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
692 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
694 bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
697 bool isFriendSpecified() const { return Friend_specified; }
698 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
700 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
701 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
703 bool isConstexprSpecified() const { return Constexpr_specified; }
704 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
706 void ClearConstexprSpec() {
707 Constexpr_specified = false;
708 ConstexprLoc = SourceLocation();
711 AttributePool &getAttributePool() const {
712 return Attrs.getPool();
715 /// \brief Concatenates two attribute lists.
717 /// The GCC attribute syntax allows for the following:
720 /// short __attribute__(( unused, deprecated ))
721 /// int __attribute__(( may_alias, aligned(16) )) var;
724 /// This declares 4 attributes using 2 lists. The following syntax is
725 /// also allowed and equivalent to the previous declaration.
728 /// short __attribute__((unused)) __attribute__((deprecated))
729 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
732 void addAttributes(AttributeList *AL) {
736 bool hasAttributes() const { return !Attrs.empty(); }
738 ParsedAttributes &getAttributes() { return Attrs; }
739 const ParsedAttributes &getAttributes() const { return Attrs; }
741 void takeAttributesFrom(ParsedAttributes &attrs) {
742 Attrs.takeAllFrom(attrs);
745 /// Finish - This does final analysis of the declspec, issuing diagnostics for
746 /// things like "_Imaginary" (lacking an FP type). After calling this method,
747 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
748 void Finish(Sema &S, const PrintingPolicy &Policy);
750 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
754 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
755 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
757 /// \brief Checks if this DeclSpec can stand alone, without a Declarator.
759 /// Only tag declspecs can stand alone.
760 bool isMissingDeclaratorOk();
763 /// \brief Captures information about "declaration specifiers" specific to
767 /// ObjCDeclQualifier - Qualifier used on types in method
768 /// declarations. Not all combinations are sensible. Parameters
769 /// can be one of { in, out, inout } with one of { bycopy, byref }.
770 /// Returns can either be { oneway } or not.
772 /// This should be kept in sync with Decl::ObjCDeclQualifier.
773 enum ObjCDeclQualifier {
781 DQ_CSNullability = 0x40
784 /// PropertyAttributeKind - list of property attributes.
785 /// Keep this list in sync with LLVM's Dwarf.h ApplePropertyAttributes.
786 enum ObjCPropertyAttributeKind {
788 DQ_PR_readonly = 0x01,
791 DQ_PR_readwrite = 0x08,
794 DQ_PR_nonatomic = 0x40,
796 DQ_PR_atomic = 0x100,
798 DQ_PR_strong = 0x400,
799 DQ_PR_unsafe_unretained = 0x800,
800 DQ_PR_nullability = 0x1000,
801 DQ_PR_null_resettable = 0x2000,
806 : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
807 Nullability(0), GetterName(nullptr), SetterName(nullptr) { }
809 ObjCDeclQualifier getObjCDeclQualifier() const {
810 return (ObjCDeclQualifier)objcDeclQualifier;
812 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
813 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
815 void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
816 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
819 ObjCPropertyAttributeKind getPropertyAttributes() const {
820 return ObjCPropertyAttributeKind(PropertyAttributes);
822 void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
824 (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
827 NullabilityKind getNullability() const {
828 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
829 (getPropertyAttributes() & DQ_PR_nullability)) &&
830 "Objective-C declspec doesn't have nullability");
831 return static_cast<NullabilityKind>(Nullability);
834 SourceLocation getNullabilityLoc() const {
835 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
836 (getPropertyAttributes() & DQ_PR_nullability)) &&
837 "Objective-C declspec doesn't have nullability");
838 return NullabilityLoc;
841 void setNullability(SourceLocation loc, NullabilityKind kind) {
842 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
843 (getPropertyAttributes() & DQ_PR_nullability)) &&
844 "Set the nullability declspec or property attribute first");
845 Nullability = static_cast<unsigned>(kind);
846 NullabilityLoc = loc;
849 const IdentifierInfo *getGetterName() const { return GetterName; }
850 IdentifierInfo *getGetterName() { return GetterName; }
851 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
852 void setGetterName(IdentifierInfo *name, SourceLocation loc) {
857 const IdentifierInfo *getSetterName() const { return SetterName; }
858 IdentifierInfo *getSetterName() { return SetterName; }
859 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
860 void setSetterName(IdentifierInfo *name, SourceLocation loc) {
866 // FIXME: These two are unrelated and mutually exclusive. So perhaps
867 // we can put them in a union to reflect their mutual exclusivity
868 // (space saving is negligible).
869 unsigned objcDeclQualifier : 7;
871 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
872 unsigned PropertyAttributes : 15;
874 unsigned Nullability : 2;
876 SourceLocation NullabilityLoc;
878 IdentifierInfo *GetterName; // getter name or NULL if no getter
879 IdentifierInfo *SetterName; // setter name or NULL if no setter
880 SourceLocation GetterNameLoc; // location of the getter attribute's value
881 SourceLocation SetterNameLoc; // location of the setter attribute's value
885 /// \brief Describes the kind of unqualified-id parsed.
886 enum class UnqualifiedIdKind {
887 /// \brief An identifier.
889 /// \brief An overloaded operator name, e.g., operator+.
890 IK_OperatorFunctionId,
891 /// \brief A conversion function name, e.g., operator int.
892 IK_ConversionFunctionId,
893 /// \brief A user-defined literal name, e.g., operator "" _i.
894 IK_LiteralOperatorId,
895 /// \brief A constructor name.
897 /// \brief A constructor named via a template-id.
898 IK_ConstructorTemplateId,
899 /// \brief A destructor name.
901 /// \brief A template-id, e.g., f<int>.
903 /// \brief An implicit 'self' parameter
904 IK_ImplicitSelfParam,
905 /// \brief A deduction-guide name (a template-name)
906 IK_DeductionGuideName
909 /// \brief Represents a C++ unqualified-id that has been parsed.
910 class UnqualifiedId {
912 UnqualifiedId(const UnqualifiedId &Other) = delete;
913 const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
916 /// \brief Describes the kind of unqualified-id parsed.
917 UnqualifiedIdKind Kind;
920 /// \brief The kind of overloaded operator.
921 OverloadedOperatorKind Operator;
923 /// \brief The source locations of the individual tokens that name
924 /// the operator, e.g., the "new", "[", and "]" tokens in
927 /// Different operators have different numbers of tokens in their name,
928 /// up to three. Any remaining source locations in this array will be
929 /// set to an invalid value for operators with fewer than three tokens.
930 unsigned SymbolLocations[3];
933 /// \brief Anonymous union that holds extra data associated with the
934 /// parsed unqualified-id.
936 /// \brief When Kind == IK_Identifier, the parsed identifier, or when
937 /// Kind == IK_UserLiteralId, the identifier suffix.
938 IdentifierInfo *Identifier;
940 /// \brief When Kind == IK_OperatorFunctionId, the overloaded operator
942 struct OFI OperatorFunctionId;
944 /// \brief When Kind == IK_ConversionFunctionId, the type that the
945 /// conversion function names.
946 UnionParsedType ConversionFunctionId;
948 /// \brief When Kind == IK_ConstructorName, the class-name of the type
949 /// whose constructor is being referenced.
950 UnionParsedType ConstructorName;
952 /// \brief When Kind == IK_DestructorName, the type referred to by the
954 UnionParsedType DestructorName;
956 /// \brief When Kind == IK_DeductionGuideName, the parsed template-name.
957 UnionParsedTemplateTy TemplateName;
959 /// \brief When Kind == IK_TemplateId or IK_ConstructorTemplateId,
960 /// the template-id annotation that contains the template name and
961 /// template arguments.
962 TemplateIdAnnotation *TemplateId;
965 /// \brief The location of the first token that describes this unqualified-id,
966 /// which will be the location of the identifier, "operator" keyword,
967 /// tilde (for a destructor), or the template name of a template-id.
968 SourceLocation StartLocation;
970 /// \brief The location of the last token that describes this unqualified-id.
971 SourceLocation EndLocation;
974 : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
976 /// \brief Clear out this unqualified-id, setting it to default (invalid)
979 Kind = UnqualifiedIdKind::IK_Identifier;
980 Identifier = nullptr;
981 StartLocation = SourceLocation();
982 EndLocation = SourceLocation();
985 /// \brief Determine whether this unqualified-id refers to a valid name.
986 bool isValid() const { return StartLocation.isValid(); }
988 /// \brief Determine whether this unqualified-id refers to an invalid name.
989 bool isInvalid() const { return !isValid(); }
991 /// \brief Determine what kind of name we have.
992 UnqualifiedIdKind getKind() const { return Kind; }
993 void setKind(UnqualifiedIdKind kind) { Kind = kind; }
995 /// \brief Specify that this unqualified-id was parsed as an identifier.
997 /// \param Id the parsed identifier.
998 /// \param IdLoc the location of the parsed identifier.
999 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1000 Kind = UnqualifiedIdKind::IK_Identifier;
1001 Identifier = const_cast<IdentifierInfo *>(Id);
1002 StartLocation = EndLocation = IdLoc;
1005 /// \brief Specify that this unqualified-id was parsed as an
1006 /// operator-function-id.
1008 /// \param OperatorLoc the location of the 'operator' keyword.
1010 /// \param Op the overloaded operator.
1012 /// \param SymbolLocations the locations of the individual operator symbols
1013 /// in the operator.
1014 void setOperatorFunctionId(SourceLocation OperatorLoc,
1015 OverloadedOperatorKind Op,
1016 SourceLocation SymbolLocations[3]);
1018 /// \brief Specify that this unqualified-id was parsed as a
1019 /// conversion-function-id.
1021 /// \param OperatorLoc the location of the 'operator' keyword.
1023 /// \param Ty the type to which this conversion function is converting.
1025 /// \param EndLoc the location of the last token that makes up the type name.
1026 void setConversionFunctionId(SourceLocation OperatorLoc,
1028 SourceLocation EndLoc) {
1029 Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1030 StartLocation = OperatorLoc;
1031 EndLocation = EndLoc;
1032 ConversionFunctionId = Ty;
1035 /// \brief Specific that this unqualified-id was parsed as a
1036 /// literal-operator-id.
1038 /// \param Id the parsed identifier.
1040 /// \param OpLoc the location of the 'operator' keyword.
1042 /// \param IdLoc the location of the identifier.
1043 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1044 SourceLocation IdLoc) {
1045 Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1046 Identifier = const_cast<IdentifierInfo *>(Id);
1047 StartLocation = OpLoc;
1048 EndLocation = IdLoc;
1051 /// \brief Specify that this unqualified-id was parsed as a constructor name.
1053 /// \param ClassType the class type referred to by the constructor name.
1055 /// \param ClassNameLoc the location of the class name.
1057 /// \param EndLoc the location of the last token that makes up the type name.
1058 void setConstructorName(ParsedType ClassType,
1059 SourceLocation ClassNameLoc,
1060 SourceLocation EndLoc) {
1061 Kind = UnqualifiedIdKind::IK_ConstructorName;
1062 StartLocation = ClassNameLoc;
1063 EndLocation = EndLoc;
1064 ConstructorName = ClassType;
1067 /// \brief Specify that this unqualified-id was parsed as a
1068 /// template-id that names a constructor.
1070 /// \param TemplateId the template-id annotation that describes the parsed
1071 /// template-id. This UnqualifiedId instance will take ownership of the
1072 /// \p TemplateId and will free it on destruction.
1073 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1075 /// \brief Specify that this unqualified-id was parsed as a destructor name.
1077 /// \param TildeLoc the location of the '~' that introduces the destructor
1080 /// \param ClassType the name of the class referred to by the destructor name.
1081 void setDestructorName(SourceLocation TildeLoc,
1082 ParsedType ClassType,
1083 SourceLocation EndLoc) {
1084 Kind = UnqualifiedIdKind::IK_DestructorName;
1085 StartLocation = TildeLoc;
1086 EndLocation = EndLoc;
1087 DestructorName = ClassType;
1090 /// \brief Specify that this unqualified-id was parsed as a template-id.
1092 /// \param TemplateId the template-id annotation that describes the parsed
1093 /// template-id. This UnqualifiedId instance will take ownership of the
1094 /// \p TemplateId and will free it on destruction.
1095 void setTemplateId(TemplateIdAnnotation *TemplateId);
1097 /// \brief Specify that this unqualified-id was parsed as a template-name for
1098 /// a deduction-guide.
1100 /// \param Template The parsed template-name.
1101 /// \param TemplateLoc The location of the parsed template-name.
1102 void setDeductionGuideName(ParsedTemplateTy Template,
1103 SourceLocation TemplateLoc) {
1104 Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1105 TemplateName = Template;
1106 StartLocation = EndLocation = TemplateLoc;
1109 /// \brief Return the source range that covers this unqualified-id.
1110 SourceRange getSourceRange() const LLVM_READONLY {
1111 return SourceRange(StartLocation, EndLocation);
1113 SourceLocation getLocStart() const LLVM_READONLY { return StartLocation; }
1114 SourceLocation getLocEnd() const LLVM_READONLY { return EndLocation; }
1117 /// \brief A set of tokens that has been cached for later parsing.
1118 typedef SmallVector<Token, 4> CachedTokens;
1120 /// \brief One instance of this struct is used for each type in a
1121 /// declarator that is parsed.
1123 /// This is intended to be a small value object.
1124 struct DeclaratorChunk {
1126 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1129 /// Loc - The place where this type was defined.
1131 /// EndLoc - If valid, the place where this chunck ends.
1132 SourceLocation EndLoc;
1134 SourceRange getSourceRange() const {
1135 if (EndLoc.isInvalid())
1136 return SourceRange(Loc, Loc);
1137 return SourceRange(Loc, EndLoc);
1140 struct TypeInfoCommon {
1141 AttributeList *AttrList;
1144 struct PointerTypeInfo : TypeInfoCommon {
1145 /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1146 unsigned TypeQuals : 5;
1148 /// The location of the const-qualifier, if any.
1149 unsigned ConstQualLoc;
1151 /// The location of the volatile-qualifier, if any.
1152 unsigned VolatileQualLoc;
1154 /// The location of the restrict-qualifier, if any.
1155 unsigned RestrictQualLoc;
1157 /// The location of the _Atomic-qualifier, if any.
1158 unsigned AtomicQualLoc;
1160 /// The location of the __unaligned-qualifier, if any.
1161 unsigned UnalignedQualLoc;
1167 struct ReferenceTypeInfo : TypeInfoCommon {
1168 /// The type qualifier: restrict. [GNU] C++ extension
1169 bool HasRestrict : 1;
1170 /// True if this is an lvalue reference, false if it's an rvalue reference.
1176 struct ArrayTypeInfo : TypeInfoCommon {
1177 /// The type qualifiers for the array:
1178 /// const/volatile/restrict/__unaligned/_Atomic.
1179 unsigned TypeQuals : 5;
1181 /// True if this dimension included the 'static' keyword.
1182 unsigned hasStatic : 1;
1184 /// True if this dimension was [*]. In this case, NumElts is null.
1185 unsigned isStar : 1;
1187 /// This is the size of the array, or null if [] or [*] was specified.
1188 /// Since the parser is multi-purpose, and we don't want to impose a root
1189 /// expression class on all clients, NumElts is untyped.
1195 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1196 /// declarator is parsed. There are two interesting styles of parameters
1198 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1199 /// lists will have information about the identifier, but no type information.
1200 /// Parameter type lists will have type info (if the actions module provides
1201 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1203 IdentifierInfo *Ident;
1204 SourceLocation IdentLoc;
1207 /// DefaultArgTokens - When the parameter's default argument
1208 /// cannot be parsed immediately (because it occurs within the
1209 /// declaration of a member function), it will be stored here as a
1210 /// sequence of tokens to be parsed once the class definition is
1211 /// complete. Non-NULL indicates that there is a default argument.
1212 std::unique_ptr<CachedTokens> DefaultArgTokens;
1214 ParamInfo() = default;
1215 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1217 std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1218 : Ident(ident), IdentLoc(iloc), Param(param),
1219 DefaultArgTokens(std::move(DefArgTokens)) {}
1222 struct TypeAndRange {
1227 struct FunctionTypeInfo : TypeInfoCommon {
1228 /// hasPrototype - This is true if the function had at least one typed
1229 /// parameter. If the function is () or (a,b,c), then it has no prototype,
1230 /// and is treated as a K&R-style function.
1231 unsigned hasPrototype : 1;
1233 /// isVariadic - If this function has a prototype, and if that
1234 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1235 /// contains the location of the ellipsis.
1236 unsigned isVariadic : 1;
1238 /// Can this declaration be a constructor-style initializer?
1239 unsigned isAmbiguous : 1;
1241 /// \brief Whether the ref-qualifier (if any) is an lvalue reference.
1242 /// Otherwise, it's an rvalue reference.
1243 unsigned RefQualifierIsLValueRef : 1;
1245 /// The type qualifiers: const/volatile/restrict/__unaligned
1246 /// The qualifier bitmask values are the same as in QualType.
1247 unsigned TypeQuals : 4;
1249 /// ExceptionSpecType - An ExceptionSpecificationType value.
1250 unsigned ExceptionSpecType : 4;
1252 /// DeleteParams - If this is true, we need to delete[] Params.
1253 unsigned DeleteParams : 1;
1255 /// HasTrailingReturnType - If this is true, a trailing return type was
1257 unsigned HasTrailingReturnType : 1;
1259 /// The location of the left parenthesis in the source.
1262 /// When isVariadic is true, the location of the ellipsis in the source.
1263 unsigned EllipsisLoc;
1265 /// The location of the right parenthesis in the source.
1268 /// NumParams - This is the number of formal parameters specified by the
1272 /// NumExceptionsOrDecls - This is the number of types in the
1273 /// dynamic-exception-decl, if the function has one. In C, this is the
1274 /// number of declarations in the function prototype.
1275 unsigned NumExceptionsOrDecls;
1277 /// \brief The location of the ref-qualifier, if any.
1279 /// If this is an invalid location, there is no ref-qualifier.
1280 unsigned RefQualifierLoc;
1282 /// \brief The location of the const-qualifier, if any.
1284 /// If this is an invalid location, there is no const-qualifier.
1285 unsigned ConstQualifierLoc;
1287 /// \brief The location of the volatile-qualifier, if any.
1289 /// If this is an invalid location, there is no volatile-qualifier.
1290 unsigned VolatileQualifierLoc;
1292 /// \brief The location of the restrict-qualifier, if any.
1294 /// If this is an invalid location, there is no restrict-qualifier.
1295 unsigned RestrictQualifierLoc;
1297 /// \brief The location of the 'mutable' qualifer in a lambda-declarator, if
1299 unsigned MutableLoc;
1301 /// \brief The beginning location of the exception specification, if any.
1302 unsigned ExceptionSpecLocBeg;
1304 /// \brief The end location of the exception specification, if any.
1305 unsigned ExceptionSpecLocEnd;
1307 /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1308 /// describe the parameters specified by this function declarator. null if
1309 /// there are no parameters specified.
1313 /// \brief Pointer to a new[]'d array of TypeAndRange objects that
1314 /// contain the types in the function's dynamic exception specification
1315 /// and their locations, if there is one.
1316 TypeAndRange *Exceptions;
1318 /// \brief Pointer to the expression in the noexcept-specifier of this
1319 /// function, if it has one.
1322 /// \brief Pointer to the cached tokens for an exception-specification
1323 /// that has not yet been parsed.
1324 CachedTokens *ExceptionSpecTokens;
1326 /// Pointer to a new[]'d array of declarations that need to be available
1327 /// for lookup inside the function body, if one exists. Does not exist in
1329 NamedDecl **DeclsInPrototype;
1332 /// \brief If HasTrailingReturnType is true, this is the trailing return
1334 UnionParsedType TrailingReturnType;
1336 /// \brief Reset the parameter list to having zero parameters.
1338 /// This is used in various places for error recovery.
1340 for (unsigned I = 0; I < NumParams; ++I)
1341 Params[I].DefaultArgTokens.reset();
1344 DeleteParams = false;
1352 switch (getExceptionSpecType()) {
1356 delete[] Exceptions;
1359 delete ExceptionSpecTokens;
1362 if (NumExceptionsOrDecls != 0)
1363 delete[] DeclsInPrototype;
1368 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1369 /// like "void foo(a,b,c)". In a function definition, this will be followed
1370 /// by the parameter type definitions.
1371 bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1373 SourceLocation getLParenLoc() const {
1374 return SourceLocation::getFromRawEncoding(LParenLoc);
1377 SourceLocation getEllipsisLoc() const {
1378 return SourceLocation::getFromRawEncoding(EllipsisLoc);
1381 SourceLocation getRParenLoc() const {
1382 return SourceLocation::getFromRawEncoding(RParenLoc);
1385 SourceLocation getExceptionSpecLocBeg() const {
1386 return SourceLocation::getFromRawEncoding(ExceptionSpecLocBeg);
1389 SourceLocation getExceptionSpecLocEnd() const {
1390 return SourceLocation::getFromRawEncoding(ExceptionSpecLocEnd);
1393 SourceRange getExceptionSpecRange() const {
1394 return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1397 /// \brief Retrieve the location of the ref-qualifier, if any.
1398 SourceLocation getRefQualifierLoc() const {
1399 return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1402 /// \brief Retrieve the location of the 'const' qualifier, if any.
1403 SourceLocation getConstQualifierLoc() const {
1404 return SourceLocation::getFromRawEncoding(ConstQualifierLoc);
1407 /// \brief Retrieve the location of the 'volatile' qualifier, if any.
1408 SourceLocation getVolatileQualifierLoc() const {
1409 return SourceLocation::getFromRawEncoding(VolatileQualifierLoc);
1412 /// \brief Retrieve the location of the 'restrict' qualifier, if any.
1413 SourceLocation getRestrictQualifierLoc() const {
1414 return SourceLocation::getFromRawEncoding(RestrictQualifierLoc);
1417 /// \brief Retrieve the location of the 'mutable' qualifier, if any.
1418 SourceLocation getMutableLoc() const {
1419 return SourceLocation::getFromRawEncoding(MutableLoc);
1422 /// \brief Determine whether this function declaration contains a
1424 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1426 /// \brief Determine whether this lambda-declarator contains a 'mutable'
1428 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1430 /// \brief Get the type of exception specification this function has.
1431 ExceptionSpecificationType getExceptionSpecType() const {
1432 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1435 /// \brief Get the number of dynamic exception specifications.
1436 unsigned getNumExceptions() const {
1437 assert(ExceptionSpecType != EST_None);
1438 return NumExceptionsOrDecls;
1441 /// \brief Get the non-parameter decls defined within this function
1442 /// prototype. Typically these are tag declarations.
1443 ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1444 assert(ExceptionSpecType == EST_None);
1445 return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1448 /// \brief Determine whether this function declarator had a
1449 /// trailing-return-type.
1450 bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1452 /// \brief Get the trailing-return-type for this function declarator.
1453 ParsedType getTrailingReturnType() const { return TrailingReturnType; }
1456 struct BlockPointerTypeInfo : TypeInfoCommon {
1457 /// For now, sema will catch these as invalid.
1458 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1459 unsigned TypeQuals : 5;
1465 struct MemberPointerTypeInfo : TypeInfoCommon {
1466 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1467 unsigned TypeQuals : 5;
1468 // CXXScopeSpec has a constructor, so it can't be a direct member.
1469 // So we need some pointer-aligned storage and a bit of trickery.
1470 alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1471 CXXScopeSpec &Scope() {
1472 return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1474 const CXXScopeSpec &Scope() const {
1475 return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1478 Scope().~CXXScopeSpec();
1482 struct PipeTypeInfo : TypeInfoCommon {
1483 /// The access writes.
1484 unsigned AccessWrites : 3;
1490 TypeInfoCommon Common;
1491 PointerTypeInfo Ptr;
1492 ReferenceTypeInfo Ref;
1494 FunctionTypeInfo Fun;
1495 BlockPointerTypeInfo Cls;
1496 MemberPointerTypeInfo Mem;
1497 PipeTypeInfo PipeInfo;
1502 case DeclaratorChunk::Function: return Fun.destroy();
1503 case DeclaratorChunk::Pointer: return Ptr.destroy();
1504 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1505 case DeclaratorChunk::Reference: return Ref.destroy();
1506 case DeclaratorChunk::Array: return Arr.destroy();
1507 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1508 case DeclaratorChunk::Paren: return;
1509 case DeclaratorChunk::Pipe: return PipeInfo.destroy();
1513 /// \brief If there are attributes applied to this declaratorchunk, return
1515 const AttributeList *getAttrs() const {
1516 return Common.AttrList;
1519 AttributeList *&getAttrListRef() {
1520 return Common.AttrList;
1523 /// \brief Return a DeclaratorChunk for a pointer.
1524 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1525 SourceLocation ConstQualLoc,
1526 SourceLocation VolatileQualLoc,
1527 SourceLocation RestrictQualLoc,
1528 SourceLocation AtomicQualLoc,
1529 SourceLocation UnalignedQualLoc) {
1533 I.Ptr.TypeQuals = TypeQuals;
1534 I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding();
1535 I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1536 I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1537 I.Ptr.AtomicQualLoc = AtomicQualLoc.getRawEncoding();
1538 I.Ptr.UnalignedQualLoc = UnalignedQualLoc.getRawEncoding();
1539 I.Ptr.AttrList = nullptr;
1543 /// \brief Return a DeclaratorChunk for a reference.
1544 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1549 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1550 I.Ref.LValueRef = lvalue;
1551 I.Ref.AttrList = nullptr;
1555 /// \brief Return a DeclaratorChunk for an array.
1556 static DeclaratorChunk getArray(unsigned TypeQuals,
1557 bool isStatic, bool isStar, Expr *NumElts,
1558 SourceLocation LBLoc, SourceLocation RBLoc) {
1563 I.Arr.AttrList = nullptr;
1564 I.Arr.TypeQuals = TypeQuals;
1565 I.Arr.hasStatic = isStatic;
1566 I.Arr.isStar = isStar;
1567 I.Arr.NumElts = NumElts;
1571 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1572 /// "TheDeclarator" is the declarator that this will be added to.
1573 static DeclaratorChunk getFunction(bool HasProto,
1575 SourceLocation LParenLoc,
1576 ParamInfo *Params, unsigned NumParams,
1577 SourceLocation EllipsisLoc,
1578 SourceLocation RParenLoc,
1580 bool RefQualifierIsLvalueRef,
1581 SourceLocation RefQualifierLoc,
1582 SourceLocation ConstQualifierLoc,
1583 SourceLocation VolatileQualifierLoc,
1584 SourceLocation RestrictQualifierLoc,
1585 SourceLocation MutableLoc,
1586 ExceptionSpecificationType ESpecType,
1587 SourceRange ESpecRange,
1588 ParsedType *Exceptions,
1589 SourceRange *ExceptionRanges,
1590 unsigned NumExceptions,
1592 CachedTokens *ExceptionSpecTokens,
1593 ArrayRef<NamedDecl *> DeclsInPrototype,
1594 SourceLocation LocalRangeBegin,
1595 SourceLocation LocalRangeEnd,
1596 Declarator &TheDeclarator,
1597 TypeResult TrailingReturnType =
1600 /// \brief Return a DeclaratorChunk for a block.
1601 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1602 SourceLocation Loc) {
1604 I.Kind = BlockPointer;
1606 I.Cls.TypeQuals = TypeQuals;
1607 I.Cls.AttrList = nullptr;
1611 /// \brief Return a DeclaratorChunk for a block.
1612 static DeclaratorChunk getPipe(unsigned TypeQuals,
1613 SourceLocation Loc) {
1617 I.Cls.TypeQuals = TypeQuals;
1618 I.Cls.AttrList = nullptr;
1622 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1624 SourceLocation Loc) {
1626 I.Kind = MemberPointer;
1627 I.Loc = SS.getBeginLoc();
1629 I.Mem.TypeQuals = TypeQuals;
1630 I.Mem.AttrList = nullptr;
1631 new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1635 /// \brief Return a DeclaratorChunk for a paren.
1636 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1637 SourceLocation RParenLoc) {
1641 I.EndLoc = RParenLoc;
1642 I.Common.AttrList = nullptr;
1646 bool isParen() const {
1647 return Kind == Paren;
1651 /// A parsed C++17 decomposition declarator of the form
1652 /// '[' identifier-list ']'
1653 class DecompositionDeclarator {
1656 IdentifierInfo *Name;
1657 SourceLocation NameLoc;
1661 /// The locations of the '[' and ']' tokens.
1662 SourceLocation LSquareLoc, RSquareLoc;
1666 unsigned NumBindings : 31;
1667 unsigned DeleteBindings : 1;
1669 friend class Declarator;
1672 DecompositionDeclarator()
1673 : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1674 DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1675 DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1676 ~DecompositionDeclarator() {
1682 LSquareLoc = RSquareLoc = SourceLocation();
1687 DeleteBindings = false;
1690 ArrayRef<Binding> bindings() const {
1691 return llvm::makeArrayRef(Bindings, NumBindings);
1694 bool isSet() const { return LSquareLoc.isValid(); }
1696 SourceLocation getLSquareLoc() const { return LSquareLoc; }
1697 SourceLocation getRSquareLoc() const { return RSquareLoc; }
1698 SourceRange getSourceRange() const {
1699 return SourceRange(LSquareLoc, RSquareLoc);
1703 /// \brief Described the kind of function definition (if any) provided for
1705 enum FunctionDefinitionKind {
1712 enum class DeclaratorContext {
1713 FileContext, // File scope declaration.
1714 PrototypeContext, // Within a function prototype.
1715 ObjCResultContext, // An ObjC method result type.
1716 ObjCParameterContext,// An ObjC method parameter type.
1717 KNRTypeListContext, // K&R type definition list for formals.
1718 TypeNameContext, // Abstract declarator for types.
1719 FunctionalCastContext, // Type in a C++ functional cast expression.
1720 MemberContext, // Struct/Union field.
1721 BlockContext, // Declaration within a block in a function.
1722 ForContext, // Declaration within first part of a for loop.
1723 InitStmtContext, // Declaration within optional init stmt of if/switch.
1724 ConditionContext, // Condition declaration in a C++ if/switch/while/for.
1725 TemplateParamContext,// Within a template parameter list.
1726 CXXNewContext, // C++ new-expression.
1727 CXXCatchContext, // C++ catch exception-declaration
1728 ObjCCatchContext, // Objective-C catch exception-declaration
1729 BlockLiteralContext, // Block literal declarator.
1730 LambdaExprContext, // Lambda-expression declarator.
1731 LambdaExprParameterContext, // Lambda-expression parameter declarator.
1732 ConversionIdContext, // C++ conversion-type-id.
1733 TrailingReturnContext, // C++11 trailing-type-specifier.
1734 TemplateTypeArgContext, // Template type argument.
1735 AliasDeclContext, // C++11 alias-declaration.
1736 AliasTemplateContext // C++11 alias-declaration template.
1740 /// \brief Information about one declarator, including the parsed type
1741 /// information and the identifier.
1743 /// When the declarator is fully formed, this is turned into the appropriate
1746 /// Declarators come in two types: normal declarators and abstract declarators.
1747 /// Abstract declarators are used when parsing types, and don't have an
1748 /// identifier. Normal declarators do have ID's.
1750 /// Instances of this class should be a transient object that lives on the
1751 /// stack, not objects that are allocated in large quantities on the heap.
1760 /// \brief Where we are parsing this declarator.
1761 DeclaratorContext Context;
1763 /// The C++17 structured binding, if any. This is an alternative to a Name.
1764 DecompositionDeclarator BindingGroup;
1766 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1767 /// parsed. This is pushed from the identifier out, which means that element
1768 /// #0 will be the most closely bound to the identifier, and
1769 /// DeclTypeInfo.back() will be the least closely bound.
1770 SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1772 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1773 unsigned InvalidType : 1;
1775 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1776 unsigned GroupingParens : 1;
1778 /// FunctionDefinition - Is this Declarator for a function or member
1779 /// definition and, if so, what kind?
1781 /// Actually a FunctionDefinitionKind.
1782 unsigned FunctionDefinition : 2;
1784 /// \brief Is this Declarator a redeclaration?
1785 unsigned Redeclaration : 1;
1787 /// \brief true if the declaration is preceded by \c __extension__.
1788 unsigned Extension : 1;
1790 /// Indicates whether this is an Objective-C instance variable.
1791 unsigned ObjCIvar : 1;
1793 /// Indicates whether this is an Objective-C 'weak' property.
1794 unsigned ObjCWeakProperty : 1;
1796 /// Indicates whether the InlineParams / InlineBindings storage has been used.
1797 unsigned InlineStorageUsed : 1;
1799 /// Attrs - Attributes.
1800 ParsedAttributes Attrs;
1802 /// \brief The asm label, if specified.
1808 /// InlineParams - This is a local array used for the first function decl
1809 /// chunk to avoid going to the heap for the common case when we have one
1810 /// function chunk in the declarator.
1811 DeclaratorChunk::ParamInfo InlineParams[16];
1812 DecompositionDeclarator::Binding InlineBindings[16];
1817 /// \brief If this is the second or subsequent declarator in this declaration,
1818 /// the location of the comma before this declarator.
1819 SourceLocation CommaLoc;
1821 /// \brief If provided, the source location of the ellipsis used to describe
1822 /// this declarator as a parameter pack.
1823 SourceLocation EllipsisLoc;
1825 friend struct DeclaratorChunk;
1828 Declarator(const DeclSpec &ds, DeclaratorContext C)
1829 : DS(ds), Range(ds.getSourceRange()), Context(C),
1830 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1831 GroupingParens(false), FunctionDefinition(FDK_Declaration),
1832 Redeclaration(false), Extension(false), ObjCIvar(false),
1833 ObjCWeakProperty(false), InlineStorageUsed(false),
1834 Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr) {}
1839 /// getDeclSpec - Return the declaration-specifier that this declarator was
1841 const DeclSpec &getDeclSpec() const { return DS; }
1843 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1844 /// should be used with extreme care: declspecs can often be shared between
1845 /// multiple declarators, so mutating the DeclSpec affects all of the
1846 /// Declarators. This should only be done when the declspec is known to not
1847 /// be shared or when in error recovery etc.
1848 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1850 AttributePool &getAttributePool() const {
1851 return Attrs.getPool();
1854 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1855 /// nested-name-specifier) that is part of the declarator-id.
1856 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1857 CXXScopeSpec &getCXXScopeSpec() { return SS; }
1859 /// \brief Retrieve the name specified by this declarator.
1860 UnqualifiedId &getName() { return Name; }
1862 const DecompositionDeclarator &getDecompositionDeclarator() const {
1863 return BindingGroup;
1866 DeclaratorContext getContext() const { return Context; }
1868 bool isPrototypeContext() const {
1869 return (Context == DeclaratorContext::PrototypeContext ||
1870 Context == DeclaratorContext::ObjCParameterContext ||
1871 Context == DeclaratorContext::ObjCResultContext ||
1872 Context == DeclaratorContext::LambdaExprParameterContext);
1875 /// \brief Get the source range that spans this declarator.
1876 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1877 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1878 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1880 void SetSourceRange(SourceRange R) { Range = R; }
1881 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1883 void SetRangeBegin(SourceLocation Loc) {
1884 if (!Loc.isInvalid())
1885 Range.setBegin(Loc);
1887 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1888 void SetRangeEnd(SourceLocation Loc) {
1889 if (!Loc.isInvalid())
1892 /// ExtendWithDeclSpec - Extend the declarator source range to include the
1893 /// given declspec, unless its location is invalid. Adopts the range start if
1894 /// the current range start is invalid.
1895 void ExtendWithDeclSpec(const DeclSpec &DS) {
1896 SourceRange SR = DS.getSourceRange();
1897 if (Range.getBegin().isInvalid())
1898 Range.setBegin(SR.getBegin());
1899 if (!SR.getEnd().isInvalid())
1900 Range.setEnd(SR.getEnd());
1903 /// \brief Reset the contents of this Declarator.
1907 Range = DS.getSourceRange();
1908 BindingGroup.clear();
1910 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1911 DeclTypeInfo[i].destroy();
1912 DeclTypeInfo.clear();
1915 InlineStorageUsed = false;
1917 ObjCWeakProperty = false;
1918 CommaLoc = SourceLocation();
1919 EllipsisLoc = SourceLocation();
1922 /// mayOmitIdentifier - Return true if the identifier is either optional or
1923 /// not allowed. This is true for typenames, prototypes, and template
1924 /// parameter lists.
1925 bool mayOmitIdentifier() const {
1927 case DeclaratorContext::FileContext:
1928 case DeclaratorContext::KNRTypeListContext:
1929 case DeclaratorContext::MemberContext:
1930 case DeclaratorContext::BlockContext:
1931 case DeclaratorContext::ForContext:
1932 case DeclaratorContext::InitStmtContext:
1933 case DeclaratorContext::ConditionContext:
1936 case DeclaratorContext::TypeNameContext:
1937 case DeclaratorContext::FunctionalCastContext:
1938 case DeclaratorContext::AliasDeclContext:
1939 case DeclaratorContext::AliasTemplateContext:
1940 case DeclaratorContext::PrototypeContext:
1941 case DeclaratorContext::LambdaExprParameterContext:
1942 case DeclaratorContext::ObjCParameterContext:
1943 case DeclaratorContext::ObjCResultContext:
1944 case DeclaratorContext::TemplateParamContext:
1945 case DeclaratorContext::CXXNewContext:
1946 case DeclaratorContext::CXXCatchContext:
1947 case DeclaratorContext::ObjCCatchContext:
1948 case DeclaratorContext::BlockLiteralContext:
1949 case DeclaratorContext::LambdaExprContext:
1950 case DeclaratorContext::ConversionIdContext:
1951 case DeclaratorContext::TemplateTypeArgContext:
1952 case DeclaratorContext::TrailingReturnContext:
1955 llvm_unreachable("unknown context kind!");
1958 /// mayHaveIdentifier - Return true if the identifier is either optional or
1959 /// required. This is true for normal declarators and prototypes, but not
1961 bool mayHaveIdentifier() const {
1963 case DeclaratorContext::FileContext:
1964 case DeclaratorContext::KNRTypeListContext:
1965 case DeclaratorContext::MemberContext:
1966 case DeclaratorContext::BlockContext:
1967 case DeclaratorContext::ForContext:
1968 case DeclaratorContext::InitStmtContext:
1969 case DeclaratorContext::ConditionContext:
1970 case DeclaratorContext::PrototypeContext:
1971 case DeclaratorContext::LambdaExprParameterContext:
1972 case DeclaratorContext::TemplateParamContext:
1973 case DeclaratorContext::CXXCatchContext:
1974 case DeclaratorContext::ObjCCatchContext:
1977 case DeclaratorContext::TypeNameContext:
1978 case DeclaratorContext::FunctionalCastContext:
1979 case DeclaratorContext::CXXNewContext:
1980 case DeclaratorContext::AliasDeclContext:
1981 case DeclaratorContext::AliasTemplateContext:
1982 case DeclaratorContext::ObjCParameterContext:
1983 case DeclaratorContext::ObjCResultContext:
1984 case DeclaratorContext::BlockLiteralContext:
1985 case DeclaratorContext::LambdaExprContext:
1986 case DeclaratorContext::ConversionIdContext:
1987 case DeclaratorContext::TemplateTypeArgContext:
1988 case DeclaratorContext::TrailingReturnContext:
1991 llvm_unreachable("unknown context kind!");
1994 /// Return true if the context permits a C++17 decomposition declarator.
1995 bool mayHaveDecompositionDeclarator() const {
1997 case DeclaratorContext::FileContext:
1998 // FIXME: It's not clear that the proposal meant to allow file-scope
1999 // structured bindings, but it does.
2000 case DeclaratorContext::BlockContext:
2001 case DeclaratorContext::ForContext:
2002 case DeclaratorContext::InitStmtContext:
2003 case DeclaratorContext::ConditionContext:
2006 case DeclaratorContext::MemberContext:
2007 case DeclaratorContext::PrototypeContext:
2008 case DeclaratorContext::TemplateParamContext:
2012 // These contexts don't allow any kind of non-abstract declarator.
2013 case DeclaratorContext::KNRTypeListContext:
2014 case DeclaratorContext::TypeNameContext:
2015 case DeclaratorContext::FunctionalCastContext:
2016 case DeclaratorContext::AliasDeclContext:
2017 case DeclaratorContext::AliasTemplateContext:
2018 case DeclaratorContext::LambdaExprParameterContext:
2019 case DeclaratorContext::ObjCParameterContext:
2020 case DeclaratorContext::ObjCResultContext:
2021 case DeclaratorContext::CXXNewContext:
2022 case DeclaratorContext::CXXCatchContext:
2023 case DeclaratorContext::ObjCCatchContext:
2024 case DeclaratorContext::BlockLiteralContext:
2025 case DeclaratorContext::LambdaExprContext:
2026 case DeclaratorContext::ConversionIdContext:
2027 case DeclaratorContext::TemplateTypeArgContext:
2028 case DeclaratorContext::TrailingReturnContext:
2031 llvm_unreachable("unknown context kind!");
2034 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2035 /// followed by a C++ direct initializer, e.g. "int x(1);".
2036 bool mayBeFollowedByCXXDirectInit() const {
2037 if (hasGroupingParens()) return false;
2039 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2042 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2043 Context != DeclaratorContext::FileContext)
2046 // Special names can't have direct initializers.
2047 if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2051 case DeclaratorContext::FileContext:
2052 case DeclaratorContext::BlockContext:
2053 case DeclaratorContext::ForContext:
2054 case DeclaratorContext::InitStmtContext:
2057 case DeclaratorContext::ConditionContext:
2058 // This may not be followed by a direct initializer, but it can't be a
2059 // function declaration either, and we'd prefer to perform a tentative
2060 // parse in order to produce the right diagnostic.
2063 case DeclaratorContext::KNRTypeListContext:
2064 case DeclaratorContext::MemberContext:
2065 case DeclaratorContext::PrototypeContext:
2066 case DeclaratorContext::LambdaExprParameterContext:
2067 case DeclaratorContext::ObjCParameterContext:
2068 case DeclaratorContext::ObjCResultContext:
2069 case DeclaratorContext::TemplateParamContext:
2070 case DeclaratorContext::CXXCatchContext:
2071 case DeclaratorContext::ObjCCatchContext:
2072 case DeclaratorContext::TypeNameContext:
2073 case DeclaratorContext::FunctionalCastContext: // FIXME
2074 case DeclaratorContext::CXXNewContext:
2075 case DeclaratorContext::AliasDeclContext:
2076 case DeclaratorContext::AliasTemplateContext:
2077 case DeclaratorContext::BlockLiteralContext:
2078 case DeclaratorContext::LambdaExprContext:
2079 case DeclaratorContext::ConversionIdContext:
2080 case DeclaratorContext::TemplateTypeArgContext:
2081 case DeclaratorContext::TrailingReturnContext:
2084 llvm_unreachable("unknown context kind!");
2087 /// isPastIdentifier - Return true if we have parsed beyond the point where
2088 /// the name would appear. (This may happen even if we haven't actually parsed
2089 /// a name, perhaps because this context doesn't require one.)
2090 bool isPastIdentifier() const { return Name.isValid(); }
2092 /// hasName - Whether this declarator has a name, which might be an
2093 /// identifier (accessible via getIdentifier()) or some kind of
2094 /// special C++ name (constructor, destructor, etc.), or a structured
2095 /// binding (which is not exactly a name, but occupies the same position).
2096 bool hasName() const {
2097 return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2098 Name.Identifier || isDecompositionDeclarator();
2101 /// Return whether this declarator is a decomposition declarator.
2102 bool isDecompositionDeclarator() const {
2103 return BindingGroup.isSet();
2106 IdentifierInfo *getIdentifier() const {
2107 if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2108 return Name.Identifier;
2112 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2114 /// \brief Set the name of this declarator to be the given identifier.
2115 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2116 Name.setIdentifier(Id, IdLoc);
2119 /// Set the decomposition bindings for this declarator.
2121 setDecompositionBindings(SourceLocation LSquareLoc,
2122 ArrayRef<DecompositionDeclarator::Binding> Bindings,
2123 SourceLocation RSquareLoc);
2125 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2126 /// EndLoc, which should be the last token of the chunk.
2127 void AddTypeInfo(const DeclaratorChunk &TI,
2128 ParsedAttributes &attrs,
2129 SourceLocation EndLoc) {
2130 DeclTypeInfo.push_back(TI);
2131 DeclTypeInfo.back().getAttrListRef() = attrs.getList();
2132 getAttributePool().takeAllFrom(attrs.getPool());
2134 if (!EndLoc.isInvalid())
2135 SetRangeEnd(EndLoc);
2138 /// \brief Add a new innermost chunk to this declarator.
2139 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2140 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2143 /// \brief Return the number of types applied to this declarator.
2144 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2146 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
2147 /// closest to the identifier.
2148 const DeclaratorChunk &getTypeObject(unsigned i) const {
2149 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2150 return DeclTypeInfo[i];
2152 DeclaratorChunk &getTypeObject(unsigned i) {
2153 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2154 return DeclTypeInfo[i];
2157 typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2158 typedef llvm::iterator_range<type_object_iterator> type_object_range;
2160 /// Returns the range of type objects, from the identifier outwards.
2161 type_object_range type_objects() const {
2162 return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2165 void DropFirstTypeObject() {
2166 assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
2167 DeclTypeInfo.front().destroy();
2168 DeclTypeInfo.erase(DeclTypeInfo.begin());
2171 /// Return the innermost (closest to the declarator) chunk of this
2172 /// declarator that is not a parens chunk, or null if there are no
2173 /// non-parens chunks.
2174 const DeclaratorChunk *getInnermostNonParenChunk() const {
2175 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2176 if (!DeclTypeInfo[i].isParen())
2177 return &DeclTypeInfo[i];
2182 /// Return the outermost (furthest from the declarator) chunk of
2183 /// this declarator that is not a parens chunk, or null if there are
2184 /// no non-parens chunks.
2185 const DeclaratorChunk *getOutermostNonParenChunk() const {
2186 for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2187 if (!DeclTypeInfo[i-1].isParen())
2188 return &DeclTypeInfo[i-1];
2193 /// isArrayOfUnknownBound - This method returns true if the declarator
2194 /// is a declarator for an array of unknown bound (looking through
2196 bool isArrayOfUnknownBound() const {
2197 const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2198 return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2199 !chunk->Arr.NumElts);
2202 /// isFunctionDeclarator - This method returns true if the declarator
2203 /// is a function declarator (looking through parentheses).
2204 /// If true is returned, then the reference type parameter idx is
2205 /// assigned with the index of the declaration chunk.
2206 bool isFunctionDeclarator(unsigned& idx) const {
2207 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2208 switch (DeclTypeInfo[i].Kind) {
2209 case DeclaratorChunk::Function:
2212 case DeclaratorChunk::Paren:
2214 case DeclaratorChunk::Pointer:
2215 case DeclaratorChunk::Reference:
2216 case DeclaratorChunk::Array:
2217 case DeclaratorChunk::BlockPointer:
2218 case DeclaratorChunk::MemberPointer:
2219 case DeclaratorChunk::Pipe:
2222 llvm_unreachable("Invalid type chunk");
2227 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2228 /// this method returns true if the identifier is a function declarator
2229 /// (looking through parentheses).
2230 bool isFunctionDeclarator() const {
2232 return isFunctionDeclarator(index);
2235 /// getFunctionTypeInfo - Retrieves the function type info object
2236 /// (looking through parentheses).
2237 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2238 assert(isFunctionDeclarator() && "Not a function declarator!");
2240 isFunctionDeclarator(index);
2241 return DeclTypeInfo[index].Fun;
2244 /// getFunctionTypeInfo - Retrieves the function type info object
2245 /// (looking through parentheses).
2246 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2247 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2250 /// \brief Determine whether the declaration that will be produced from
2251 /// this declaration will be a function.
2253 /// A declaration can declare a function even if the declarator itself
2254 /// isn't a function declarator, if the type specifier refers to a function
2255 /// type. This routine checks for both cases.
2256 bool isDeclarationOfFunction() const;
2258 /// \brief Return true if this declaration appears in a context where a
2259 /// function declarator would be a function declaration.
2260 bool isFunctionDeclarationContext() const {
2261 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2265 case DeclaratorContext::FileContext:
2266 case DeclaratorContext::MemberContext:
2267 case DeclaratorContext::BlockContext:
2268 case DeclaratorContext::ForContext:
2269 case DeclaratorContext::InitStmtContext:
2272 case DeclaratorContext::ConditionContext:
2273 case DeclaratorContext::KNRTypeListContext:
2274 case DeclaratorContext::TypeNameContext:
2275 case DeclaratorContext::FunctionalCastContext:
2276 case DeclaratorContext::AliasDeclContext:
2277 case DeclaratorContext::AliasTemplateContext:
2278 case DeclaratorContext::PrototypeContext:
2279 case DeclaratorContext::LambdaExprParameterContext:
2280 case DeclaratorContext::ObjCParameterContext:
2281 case DeclaratorContext::ObjCResultContext:
2282 case DeclaratorContext::TemplateParamContext:
2283 case DeclaratorContext::CXXNewContext:
2284 case DeclaratorContext::CXXCatchContext:
2285 case DeclaratorContext::ObjCCatchContext:
2286 case DeclaratorContext::BlockLiteralContext:
2287 case DeclaratorContext::LambdaExprContext:
2288 case DeclaratorContext::ConversionIdContext:
2289 case DeclaratorContext::TemplateTypeArgContext:
2290 case DeclaratorContext::TrailingReturnContext:
2293 llvm_unreachable("unknown context kind!");
2296 /// Determine whether this declaration appears in a context where an
2297 /// expression could appear.
2298 bool isExpressionContext() const {
2300 case DeclaratorContext::FileContext:
2301 case DeclaratorContext::KNRTypeListContext:
2302 case DeclaratorContext::MemberContext:
2304 // FIXME: sizeof(...) permits an expression.
2305 case DeclaratorContext::TypeNameContext:
2307 case DeclaratorContext::FunctionalCastContext:
2308 case DeclaratorContext::AliasDeclContext:
2309 case DeclaratorContext::AliasTemplateContext:
2310 case DeclaratorContext::PrototypeContext:
2311 case DeclaratorContext::LambdaExprParameterContext:
2312 case DeclaratorContext::ObjCParameterContext:
2313 case DeclaratorContext::ObjCResultContext:
2314 case DeclaratorContext::TemplateParamContext:
2315 case DeclaratorContext::CXXNewContext:
2316 case DeclaratorContext::CXXCatchContext:
2317 case DeclaratorContext::ObjCCatchContext:
2318 case DeclaratorContext::BlockLiteralContext:
2319 case DeclaratorContext::LambdaExprContext:
2320 case DeclaratorContext::ConversionIdContext:
2321 case DeclaratorContext::TrailingReturnContext:
2324 case DeclaratorContext::BlockContext:
2325 case DeclaratorContext::ForContext:
2326 case DeclaratorContext::InitStmtContext:
2327 case DeclaratorContext::ConditionContext:
2328 case DeclaratorContext::TemplateTypeArgContext:
2332 llvm_unreachable("unknown context kind!");
2335 /// \brief Return true if a function declarator at this position would be a
2336 /// function declaration.
2337 bool isFunctionDeclaratorAFunctionDeclaration() const {
2338 if (!isFunctionDeclarationContext())
2341 for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2342 if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2348 /// \brief Determine whether a trailing return type was written (at any
2349 /// level) within this declarator.
2350 bool hasTrailingReturnType() const {
2351 for (const auto &Chunk : type_objects())
2352 if (Chunk.Kind == DeclaratorChunk::Function &&
2353 Chunk.Fun.hasTrailingReturnType())
2358 /// takeAttributes - Takes attributes from the given parsed-attributes
2359 /// set and add them to this declarator.
2361 /// These examples both add 3 attributes to "var":
2362 /// short int var __attribute__((aligned(16),common,deprecated));
2363 /// short int x, __attribute__((aligned(16)) var
2364 /// __attribute__((common,deprecated));
2366 /// Also extends the range of the declarator.
2367 void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2368 Attrs.takeAllFrom(attrs);
2370 if (!lastLoc.isInvalid())
2371 SetRangeEnd(lastLoc);
2374 const AttributeList *getAttributes() const { return Attrs.getList(); }
2375 AttributeList *getAttributes() { return Attrs.getList(); }
2377 AttributeList *&getAttrListRef() { return Attrs.getListRef(); }
2379 /// hasAttributes - do we contain any attributes?
2380 bool hasAttributes() const {
2381 if (getAttributes() || getDeclSpec().hasAttributes()) return true;
2382 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2383 if (getTypeObject(i).getAttrs())
2388 /// \brief Return a source range list of C++11 attributes associated
2389 /// with the declarator.
2390 void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2391 AttributeList *AttrList = Attrs.getList();
2393 if (AttrList->isCXX11Attribute())
2394 Ranges.push_back(AttrList->getRange());
2395 AttrList = AttrList->getNext();
2399 void setAsmLabel(Expr *E) { AsmLabel = E; }
2400 Expr *getAsmLabel() const { return AsmLabel; }
2402 void setExtension(bool Val = true) { Extension = Val; }
2403 bool getExtension() const { return Extension; }
2405 void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2406 bool isObjCIvar() const { return ObjCIvar; }
2408 void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2409 bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2411 void setInvalidType(bool Val = true) { InvalidType = Val; }
2412 bool isInvalidType() const {
2413 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2416 void setGroupingParens(bool flag) { GroupingParens = flag; }
2417 bool hasGroupingParens() const { return GroupingParens; }
2419 bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2420 SourceLocation getCommaLoc() const { return CommaLoc; }
2421 void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2423 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2424 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2425 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2427 void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2428 FunctionDefinition = Val;
2431 bool isFunctionDefinition() const {
2432 return getFunctionDefinitionKind() != FDK_Declaration;
2435 FunctionDefinitionKind getFunctionDefinitionKind() const {
2436 return (FunctionDefinitionKind)FunctionDefinition;
2439 /// Returns true if this declares a real member and not a friend.
2440 bool isFirstDeclarationOfMember() {
2441 return getContext() == DeclaratorContext::MemberContext &&
2442 !getDeclSpec().isFriendSpecified();
2445 /// Returns true if this declares a static member. This cannot be called on a
2446 /// declarator outside of a MemberContext because we won't know until
2447 /// redeclaration time if the decl is static.
2448 bool isStaticMember();
2450 /// Returns true if this declares a constructor or a destructor.
2451 bool isCtorOrDtor();
2453 void setRedeclaration(bool Val) { Redeclaration = Val; }
2454 bool isRedeclaration() const { return Redeclaration; }
2457 /// \brief This little struct is used to capture information about
2458 /// structure field declarators, which is basically just a bitfield size.
2459 struct FieldDeclarator {
2462 explicit FieldDeclarator(const DeclSpec &DS)
2463 : D(DS, DeclaratorContext::MemberContext),
2464 BitfieldSize(nullptr) {}
2467 /// \brief Represents a C++11 virt-specifier-seq.
2468 class VirtSpecifiers {
2475 // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2479 VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2481 bool SetSpecifier(Specifier VS, SourceLocation Loc,
2482 const char *&PrevSpec);
2484 bool isUnset() const { return Specifiers == 0; }
2486 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2487 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2489 bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2490 bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2491 SourceLocation getFinalLoc() const { return VS_finalLoc; }
2493 void clear() { Specifiers = 0; }
2495 static const char *getSpecifierName(Specifier VS);
2497 SourceLocation getFirstLocation() const { return FirstLocation; }
2498 SourceLocation getLastLocation() const { return LastLocation; }
2499 Specifier getLastSpecifier() const { return LastSpecifier; }
2502 unsigned Specifiers;
2503 Specifier LastSpecifier;
2505 SourceLocation VS_overrideLoc, VS_finalLoc;
2506 SourceLocation FirstLocation;
2507 SourceLocation LastLocation;
2510 enum class LambdaCaptureInitKind {
2512 CopyInit, //!< [a = b], [a = {b}]
2513 DirectInit, //!< [a(b)]
2514 ListInit //!< [a{b}]
2517 /// \brief Represents a complete lambda introducer.
2518 struct LambdaIntroducer {
2519 /// \brief An individual capture in a lambda introducer.
2520 struct LambdaCapture {
2521 LambdaCaptureKind Kind;
2524 SourceLocation EllipsisLoc;
2525 LambdaCaptureInitKind InitKind;
2527 ParsedType InitCaptureType;
2528 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2529 IdentifierInfo *Id, SourceLocation EllipsisLoc,
2530 LambdaCaptureInitKind InitKind, ExprResult Init,
2531 ParsedType InitCaptureType)
2532 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2533 InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType) {}
2537 SourceLocation DefaultLoc;
2538 LambdaCaptureDefault Default;
2539 SmallVector<LambdaCapture, 4> Captures;
2542 : Default(LCD_None) {}
2544 /// \brief Append a capture in a lambda introducer.
2545 void addCapture(LambdaCaptureKind Kind,
2548 SourceLocation EllipsisLoc,
2549 LambdaCaptureInitKind InitKind,
2551 ParsedType InitCaptureType) {
2552 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2557 } // end namespace clang
2559 #endif // LLVM_CLANG_SEMA_DECLSPEC_H