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_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;
309 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
315 // This has no corresponding Qualifiers::TQ value, because it's not treated
316 // as a qualifier in our type system.
320 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
321 /// returned by getParsedSpecifiers.
322 enum ParsedSpecifiers {
324 PQ_StorageClassSpecifier = 1,
325 PQ_TypeSpecifier = 2,
326 PQ_TypeQualifier = 4,
327 PQ_FunctionSpecifier = 8
331 // storage-class-specifier
332 /*SCS*/unsigned StorageClassSpec : 3;
333 /*TSCS*/unsigned ThreadStorageClassSpec : 2;
334 unsigned SCS_extern_in_linkage_spec : 1;
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;
348 unsigned TypeQualifiers : 5; // Bitwise OR of TQ.
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;
358 unsigned Friend_specified : 1;
360 // constexpr-specifier
361 unsigned Constexpr_specified : 1;
364 unsigned Concept_specified : 1;
367 UnionParsedType TypeRep;
373 ParsedAttributes Attrs;
375 // Scope specifier for the type spec, if applicable.
376 CXXScopeSpec TypeScope;
378 // SourceLocation info. These are null if the item wasn't specified or if
379 // the setting was synthesized.
382 SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
383 SourceRange TSWRange;
384 SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc;
385 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
386 /// typename, then this is the location of the named type (if present);
387 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
388 /// TSTNameLoc provides source range info for tag types.
389 SourceLocation TSTNameLoc;
390 SourceRange TypeofParensRange;
391 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
393 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
394 SourceLocation FS_forceinlineLoc;
395 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc, ConceptLoc;
396 SourceLocation TQ_pipeLoc;
398 WrittenBuiltinSpecs writtenBS;
399 void SaveWrittenBuiltinSpecs();
401 ObjCDeclSpec *ObjCQualifiers;
403 static bool isTypeRep(TST T) {
404 return (T == TST_typename || T == TST_typeofType ||
405 T == TST_underlyingType || T == TST_atomic);
407 static bool isExprRep(TST T) {
408 return (T == TST_typeofExpr || T == TST_decltype);
411 DeclSpec(const DeclSpec &) = delete;
412 void operator=(const DeclSpec &) = delete;
414 static bool isDeclRep(TST T) {
415 return (T == TST_enum || T == TST_struct ||
416 T == TST_interface || T == TST_union ||
420 DeclSpec(AttributeFactory &attrFactory)
421 : StorageClassSpec(SCS_unspecified),
422 ThreadStorageClassSpec(TSCS_unspecified),
423 SCS_extern_in_linkage_spec(false),
424 TypeSpecWidth(TSW_unspecified),
425 TypeSpecComplex(TSC_unspecified),
426 TypeSpecSign(TSS_unspecified),
427 TypeSpecType(TST_unspecified),
428 TypeAltiVecVector(false),
429 TypeAltiVecPixel(false),
430 TypeAltiVecBool(false),
431 TypeSpecOwned(false),
433 TypeQualifiers(TQ_unspecified),
434 FS_inline_specified(false),
435 FS_forceinline_specified(false),
436 FS_virtual_specified(false),
437 FS_explicit_specified(false),
438 FS_noreturn_specified(false),
439 Friend_specified(false),
440 Constexpr_specified(false),
441 Concept_specified(false),
444 ObjCQualifiers(nullptr) {
447 // storage-class-specifier
448 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
449 TSCS getThreadStorageClassSpec() const {
450 return (TSCS)ThreadStorageClassSpec;
452 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
453 void setExternInLinkageSpec(bool Value) {
454 SCS_extern_in_linkage_spec = Value;
457 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
458 SourceLocation getThreadStorageClassSpecLoc() const {
459 return ThreadStorageClassSpecLoc;
462 void ClearStorageClassSpecs() {
463 StorageClassSpec = DeclSpec::SCS_unspecified;
464 ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
465 SCS_extern_in_linkage_spec = false;
466 StorageClassSpecLoc = SourceLocation();
467 ThreadStorageClassSpecLoc = SourceLocation();
470 void ClearTypeSpecType() {
471 TypeSpecType = DeclSpec::TST_unspecified;
472 TypeSpecOwned = false;
473 TSTLoc = SourceLocation();
477 TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
478 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
479 TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
480 TST getTypeSpecType() const { return (TST)TypeSpecType; }
481 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
482 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
483 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
484 bool isTypeSpecOwned() const { return TypeSpecOwned; }
485 bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
486 bool isTypeSpecPipe() const { return TypeSpecPipe; }
488 ParsedType getRepAsType() const {
489 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
492 Decl *getRepAsDecl() const {
493 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
496 Expr *getRepAsExpr() const {
497 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
500 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
501 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
503 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
504 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
505 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
507 SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
508 SourceRange getTypeSpecWidthRange() const { return TSWRange; }
509 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
510 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
511 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
512 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
514 SourceLocation getTypeSpecTypeNameLoc() const {
515 assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename);
519 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
520 void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
522 bool hasAutoTypeSpec() const {
523 return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
524 TypeSpecType == TST_decltype_auto);
527 bool hasTagDefinition() const;
529 /// \brief Turn a type-specifier-type into a string like "_Bool" or "union".
530 static const char *getSpecifierName(DeclSpec::TST T,
531 const PrintingPolicy &Policy);
532 static const char *getSpecifierName(DeclSpec::TQ Q);
533 static const char *getSpecifierName(DeclSpec::TSS S);
534 static const char *getSpecifierName(DeclSpec::TSC C);
535 static const char *getSpecifierName(DeclSpec::TSW W);
536 static const char *getSpecifierName(DeclSpec::SCS S);
537 static const char *getSpecifierName(DeclSpec::TSCS S);
541 /// getTypeQualifiers - Return a set of TQs.
542 unsigned getTypeQualifiers() const { return TypeQualifiers; }
543 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
544 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
545 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
546 SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
547 SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
548 SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
550 /// \brief Clear out all of the type qualifiers.
551 void ClearTypeQualifiers() {
553 TQ_constLoc = SourceLocation();
554 TQ_restrictLoc = SourceLocation();
555 TQ_volatileLoc = SourceLocation();
556 TQ_atomicLoc = SourceLocation();
557 TQ_unalignedLoc = SourceLocation();
558 TQ_pipeLoc = SourceLocation();
561 // function-specifier
562 bool isInlineSpecified() const {
563 return FS_inline_specified | FS_forceinline_specified;
565 SourceLocation getInlineSpecLoc() const {
566 return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
569 bool isVirtualSpecified() const { return FS_virtual_specified; }
570 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
572 bool isExplicitSpecified() const { return FS_explicit_specified; }
573 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
575 bool isNoreturnSpecified() const { return FS_noreturn_specified; }
576 SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
578 void ClearFunctionSpecs() {
579 FS_inline_specified = false;
580 FS_inlineLoc = SourceLocation();
581 FS_forceinline_specified = false;
582 FS_forceinlineLoc = SourceLocation();
583 FS_virtual_specified = false;
584 FS_virtualLoc = SourceLocation();
585 FS_explicit_specified = false;
586 FS_explicitLoc = SourceLocation();
587 FS_noreturn_specified = false;
588 FS_noreturnLoc = SourceLocation();
591 /// \brief Return true if any type-specifier has been found.
592 bool hasTypeSpecifier() const {
593 return getTypeSpecType() != DeclSpec::TST_unspecified ||
594 getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
595 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
596 getTypeSpecSign() != DeclSpec::TSS_unspecified;
599 /// \brief Return a bitmask of which flavors of specifiers this
600 /// DeclSpec includes.
601 unsigned getParsedSpecifiers() const;
603 /// isEmpty - Return true if this declaration specifier is completely empty:
604 /// no tokens were parsed in the production of it.
605 bool isEmpty() const {
606 return getParsedSpecifiers() == DeclSpec::PQ_None;
609 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
610 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
612 /// These methods set the specified attribute of the DeclSpec and
613 /// return false if there was no error. If an error occurs (for
614 /// example, if we tried to set "auto" on a spec with "extern"
615 /// already set), they return true and set PrevSpec and DiagID
617 /// Diag(Loc, DiagID) << PrevSpec;
618 /// will yield a useful result.
620 /// TODO: use a more general approach that still allows these
621 /// diagnostics to be ignored when desired.
622 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
623 const char *&PrevSpec, unsigned &DiagID,
624 const PrintingPolicy &Policy);
625 bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
626 const char *&PrevSpec, unsigned &DiagID);
627 bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
628 unsigned &DiagID, const PrintingPolicy &Policy);
629 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
631 bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
633 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
634 unsigned &DiagID, const PrintingPolicy &Policy);
635 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
636 unsigned &DiagID, ParsedType Rep,
637 const PrintingPolicy &Policy);
638 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
639 unsigned &DiagID, Decl *Rep, bool Owned,
640 const PrintingPolicy &Policy);
641 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
642 SourceLocation TagNameLoc, const char *&PrevSpec,
643 unsigned &DiagID, ParsedType Rep,
644 const PrintingPolicy &Policy);
645 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
646 SourceLocation TagNameLoc, const char *&PrevSpec,
647 unsigned &DiagID, Decl *Rep, bool Owned,
648 const PrintingPolicy &Policy);
650 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
651 unsigned &DiagID, Expr *Rep,
652 const PrintingPolicy &policy);
653 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
654 const char *&PrevSpec, unsigned &DiagID,
655 const PrintingPolicy &Policy);
656 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
657 const char *&PrevSpec, unsigned &DiagID,
658 const PrintingPolicy &Policy);
659 bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
660 const char *&PrevSpec, unsigned &DiagID,
661 const PrintingPolicy &Policy);
662 bool SetTypePipe(bool isPipe, SourceLocation Loc,
663 const char *&PrevSpec, unsigned &DiagID,
664 const PrintingPolicy &Policy);
665 bool SetTypeSpecError();
666 void UpdateDeclRep(Decl *Rep) {
667 assert(isDeclRep((TST) TypeSpecType));
670 void UpdateTypeRep(ParsedType Rep) {
671 assert(isTypeRep((TST) TypeSpecType));
674 void UpdateExprRep(Expr *Rep) {
675 assert(isExprRep((TST) TypeSpecType));
679 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
680 unsigned &DiagID, const LangOptions &Lang);
682 bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
684 bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
686 bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
688 bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
690 bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
693 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
695 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
697 bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
699 bool SetConceptSpec(SourceLocation Loc, const char *&PrevSpec,
702 bool isFriendSpecified() const { return Friend_specified; }
703 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
705 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
706 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
708 bool isConstexprSpecified() const { return Constexpr_specified; }
709 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
711 bool isConceptSpecified() const { return Concept_specified; }
712 SourceLocation getConceptSpecLoc() const { return ConceptLoc; }
714 void ClearConstexprSpec() {
715 Constexpr_specified = false;
716 ConstexprLoc = SourceLocation();
719 void ClearConceptSpec() {
720 Concept_specified = false;
721 ConceptLoc = SourceLocation();
724 AttributePool &getAttributePool() const {
725 return Attrs.getPool();
728 /// \brief Concatenates two attribute lists.
730 /// The GCC attribute syntax allows for the following:
733 /// short __attribute__(( unused, deprecated ))
734 /// int __attribute__(( may_alias, aligned(16) )) var;
737 /// This declares 4 attributes using 2 lists. The following syntax is
738 /// also allowed and equivalent to the previous declaration.
741 /// short __attribute__((unused)) __attribute__((deprecated))
742 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
745 void addAttributes(AttributeList *AL) {
749 bool hasAttributes() const { return !Attrs.empty(); }
751 ParsedAttributes &getAttributes() { return Attrs; }
752 const ParsedAttributes &getAttributes() const { return Attrs; }
754 void takeAttributesFrom(ParsedAttributes &attrs) {
755 Attrs.takeAllFrom(attrs);
758 /// Finish - This does final analysis of the declspec, issuing diagnostics for
759 /// things like "_Imaginary" (lacking an FP type). After calling this method,
760 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
761 void Finish(Sema &S, const PrintingPolicy &Policy);
763 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
767 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
768 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
770 /// \brief Checks if this DeclSpec can stand alone, without a Declarator.
772 /// Only tag declspecs can stand alone.
773 bool isMissingDeclaratorOk();
776 /// \brief Captures information about "declaration specifiers" specific to
780 /// ObjCDeclQualifier - Qualifier used on types in method
781 /// declarations. Not all combinations are sensible. Parameters
782 /// can be one of { in, out, inout } with one of { bycopy, byref }.
783 /// Returns can either be { oneway } or not.
785 /// This should be kept in sync with Decl::ObjCDeclQualifier.
786 enum ObjCDeclQualifier {
794 DQ_CSNullability = 0x40
797 /// PropertyAttributeKind - list of property attributes.
798 /// Keep this list in sync with LLVM's Dwarf.h ApplePropertyAttributes.
799 enum ObjCPropertyAttributeKind {
801 DQ_PR_readonly = 0x01,
804 DQ_PR_readwrite = 0x08,
807 DQ_PR_nonatomic = 0x40,
809 DQ_PR_atomic = 0x100,
811 DQ_PR_strong = 0x400,
812 DQ_PR_unsafe_unretained = 0x800,
813 DQ_PR_nullability = 0x1000,
814 DQ_PR_null_resettable = 0x2000,
819 : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
820 Nullability(0), GetterName(nullptr), SetterName(nullptr) { }
822 ObjCDeclQualifier getObjCDeclQualifier() const {
823 return (ObjCDeclQualifier)objcDeclQualifier;
825 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
826 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
828 void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
829 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
832 ObjCPropertyAttributeKind getPropertyAttributes() const {
833 return ObjCPropertyAttributeKind(PropertyAttributes);
835 void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
837 (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
840 NullabilityKind getNullability() const {
841 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
842 (getPropertyAttributes() & DQ_PR_nullability)) &&
843 "Objective-C declspec doesn't have nullability");
844 return static_cast<NullabilityKind>(Nullability);
847 SourceLocation getNullabilityLoc() const {
848 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
849 (getPropertyAttributes() & DQ_PR_nullability)) &&
850 "Objective-C declspec doesn't have nullability");
851 return NullabilityLoc;
854 void setNullability(SourceLocation loc, NullabilityKind kind) {
855 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
856 (getPropertyAttributes() & DQ_PR_nullability)) &&
857 "Set the nullability declspec or property attribute first");
858 Nullability = static_cast<unsigned>(kind);
859 NullabilityLoc = loc;
862 const IdentifierInfo *getGetterName() const { return GetterName; }
863 IdentifierInfo *getGetterName() { return GetterName; }
864 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
865 void setGetterName(IdentifierInfo *name, SourceLocation loc) {
870 const IdentifierInfo *getSetterName() const { return SetterName; }
871 IdentifierInfo *getSetterName() { return SetterName; }
872 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
873 void setSetterName(IdentifierInfo *name, SourceLocation loc) {
879 // FIXME: These two are unrelated and mutually exclusive. So perhaps
880 // we can put them in a union to reflect their mutual exclusivity
881 // (space saving is negligible).
882 unsigned objcDeclQualifier : 7;
884 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
885 unsigned PropertyAttributes : 15;
887 unsigned Nullability : 2;
889 SourceLocation NullabilityLoc;
891 IdentifierInfo *GetterName; // getter name or NULL if no getter
892 IdentifierInfo *SetterName; // setter name or NULL if no setter
893 SourceLocation GetterNameLoc; // location of the getter attribute's value
894 SourceLocation SetterNameLoc; // location of the setter attribute's value
898 /// \brief Represents a C++ unqualified-id that has been parsed.
899 class UnqualifiedId {
901 UnqualifiedId(const UnqualifiedId &Other) = delete;
902 const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
905 /// \brief Describes the kind of unqualified-id parsed.
907 /// \brief An identifier.
909 /// \brief An overloaded operator name, e.g., operator+.
910 IK_OperatorFunctionId,
911 /// \brief A conversion function name, e.g., operator int.
912 IK_ConversionFunctionId,
913 /// \brief A user-defined literal name, e.g., operator "" _i.
914 IK_LiteralOperatorId,
915 /// \brief A constructor name.
917 /// \brief A constructor named via a template-id.
918 IK_ConstructorTemplateId,
919 /// \brief A destructor name.
921 /// \brief A template-id, e.g., f<int>.
923 /// \brief An implicit 'self' parameter
924 IK_ImplicitSelfParam,
925 /// \brief A deduction-guide name (a template-name)
926 IK_DeductionGuideName
930 /// \brief The kind of overloaded operator.
931 OverloadedOperatorKind Operator;
933 /// \brief The source locations of the individual tokens that name
934 /// the operator, e.g., the "new", "[", and "]" tokens in
937 /// Different operators have different numbers of tokens in their name,
938 /// up to three. Any remaining source locations in this array will be
939 /// set to an invalid value for operators with fewer than three tokens.
940 unsigned SymbolLocations[3];
943 /// \brief Anonymous union that holds extra data associated with the
944 /// parsed unqualified-id.
946 /// \brief When Kind == IK_Identifier, the parsed identifier, or when
947 /// Kind == IK_UserLiteralId, the identifier suffix.
948 IdentifierInfo *Identifier;
950 /// \brief When Kind == IK_OperatorFunctionId, the overloaded operator
952 struct OFI OperatorFunctionId;
954 /// \brief When Kind == IK_ConversionFunctionId, the type that the
955 /// conversion function names.
956 UnionParsedType ConversionFunctionId;
958 /// \brief When Kind == IK_ConstructorName, the class-name of the type
959 /// whose constructor is being referenced.
960 UnionParsedType ConstructorName;
962 /// \brief When Kind == IK_DestructorName, the type referred to by the
964 UnionParsedType DestructorName;
966 /// \brief When Kind == IK_DeductionGuideName, the parsed template-name.
967 UnionParsedTemplateTy TemplateName;
969 /// \brief When Kind == IK_TemplateId or IK_ConstructorTemplateId,
970 /// the template-id annotation that contains the template name and
971 /// template arguments.
972 TemplateIdAnnotation *TemplateId;
975 /// \brief The location of the first token that describes this unqualified-id,
976 /// which will be the location of the identifier, "operator" keyword,
977 /// tilde (for a destructor), or the template name of a template-id.
978 SourceLocation StartLocation;
980 /// \brief The location of the last token that describes this unqualified-id.
981 SourceLocation EndLocation;
983 UnqualifiedId() : Kind(IK_Identifier), Identifier(nullptr) { }
985 /// \brief Clear out this unqualified-id, setting it to default (invalid)
988 Kind = IK_Identifier;
989 Identifier = nullptr;
990 StartLocation = SourceLocation();
991 EndLocation = SourceLocation();
994 /// \brief Determine whether this unqualified-id refers to a valid name.
995 bool isValid() const { return StartLocation.isValid(); }
997 /// \brief Determine whether this unqualified-id refers to an invalid name.
998 bool isInvalid() const { return !isValid(); }
1000 /// \brief Determine what kind of name we have.
1001 IdKind getKind() const { return Kind; }
1002 void setKind(IdKind kind) { Kind = kind; }
1004 /// \brief Specify that this unqualified-id was parsed as an identifier.
1006 /// \param Id the parsed identifier.
1007 /// \param IdLoc the location of the parsed identifier.
1008 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1009 Kind = IK_Identifier;
1010 Identifier = const_cast<IdentifierInfo *>(Id);
1011 StartLocation = EndLocation = IdLoc;
1014 /// \brief Specify that this unqualified-id was parsed as an
1015 /// operator-function-id.
1017 /// \param OperatorLoc the location of the 'operator' keyword.
1019 /// \param Op the overloaded operator.
1021 /// \param SymbolLocations the locations of the individual operator symbols
1022 /// in the operator.
1023 void setOperatorFunctionId(SourceLocation OperatorLoc,
1024 OverloadedOperatorKind Op,
1025 SourceLocation SymbolLocations[3]);
1027 /// \brief Specify that this unqualified-id was parsed as a
1028 /// conversion-function-id.
1030 /// \param OperatorLoc the location of the 'operator' keyword.
1032 /// \param Ty the type to which this conversion function is converting.
1034 /// \param EndLoc the location of the last token that makes up the type name.
1035 void setConversionFunctionId(SourceLocation OperatorLoc,
1037 SourceLocation EndLoc) {
1038 Kind = IK_ConversionFunctionId;
1039 StartLocation = OperatorLoc;
1040 EndLocation = EndLoc;
1041 ConversionFunctionId = Ty;
1044 /// \brief Specific that this unqualified-id was parsed as a
1045 /// literal-operator-id.
1047 /// \param Id the parsed identifier.
1049 /// \param OpLoc the location of the 'operator' keyword.
1051 /// \param IdLoc the location of the identifier.
1052 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1053 SourceLocation IdLoc) {
1054 Kind = IK_LiteralOperatorId;
1055 Identifier = const_cast<IdentifierInfo *>(Id);
1056 StartLocation = OpLoc;
1057 EndLocation = IdLoc;
1060 /// \brief Specify that this unqualified-id was parsed as a constructor name.
1062 /// \param ClassType the class type referred to by the constructor name.
1064 /// \param ClassNameLoc the location of the class name.
1066 /// \param EndLoc the location of the last token that makes up the type name.
1067 void setConstructorName(ParsedType ClassType,
1068 SourceLocation ClassNameLoc,
1069 SourceLocation EndLoc) {
1070 Kind = IK_ConstructorName;
1071 StartLocation = ClassNameLoc;
1072 EndLocation = EndLoc;
1073 ConstructorName = ClassType;
1076 /// \brief Specify that this unqualified-id was parsed as a
1077 /// template-id that names a constructor.
1079 /// \param TemplateId the template-id annotation that describes the parsed
1080 /// template-id. This UnqualifiedId instance will take ownership of the
1081 /// \p TemplateId and will free it on destruction.
1082 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1084 /// \brief Specify that this unqualified-id was parsed as a destructor name.
1086 /// \param TildeLoc the location of the '~' that introduces the destructor
1089 /// \param ClassType the name of the class referred to by the destructor name.
1090 void setDestructorName(SourceLocation TildeLoc,
1091 ParsedType ClassType,
1092 SourceLocation EndLoc) {
1093 Kind = IK_DestructorName;
1094 StartLocation = TildeLoc;
1095 EndLocation = EndLoc;
1096 DestructorName = ClassType;
1099 /// \brief Specify that this unqualified-id was parsed as a template-id.
1101 /// \param TemplateId the template-id annotation that describes the parsed
1102 /// template-id. This UnqualifiedId instance will take ownership of the
1103 /// \p TemplateId and will free it on destruction.
1104 void setTemplateId(TemplateIdAnnotation *TemplateId);
1106 /// \brief Specify that this unqualified-id was parsed as a template-name for
1107 /// a deduction-guide.
1109 /// \param Template The parsed template-name.
1110 /// \param TemplateLoc The location of the parsed template-name.
1111 void setDeductionGuideName(ParsedTemplateTy Template,
1112 SourceLocation TemplateLoc) {
1113 Kind = IK_DeductionGuideName;
1114 TemplateName = Template;
1115 StartLocation = EndLocation = TemplateLoc;
1118 /// \brief Return the source range that covers this unqualified-id.
1119 SourceRange getSourceRange() const LLVM_READONLY {
1120 return SourceRange(StartLocation, EndLocation);
1122 SourceLocation getLocStart() const LLVM_READONLY { return StartLocation; }
1123 SourceLocation getLocEnd() const LLVM_READONLY { return EndLocation; }
1126 /// \brief A set of tokens that has been cached for later parsing.
1127 typedef SmallVector<Token, 4> CachedTokens;
1129 /// \brief One instance of this struct is used for each type in a
1130 /// declarator that is parsed.
1132 /// This is intended to be a small value object.
1133 struct DeclaratorChunk {
1135 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1138 /// Loc - The place where this type was defined.
1140 /// EndLoc - If valid, the place where this chunck ends.
1141 SourceLocation EndLoc;
1143 SourceRange getSourceRange() const {
1144 if (EndLoc.isInvalid())
1145 return SourceRange(Loc, Loc);
1146 return SourceRange(Loc, EndLoc);
1149 struct TypeInfoCommon {
1150 AttributeList *AttrList;
1153 struct PointerTypeInfo : TypeInfoCommon {
1154 /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1155 unsigned TypeQuals : 5;
1157 /// The location of the const-qualifier, if any.
1158 unsigned ConstQualLoc;
1160 /// The location of the volatile-qualifier, if any.
1161 unsigned VolatileQualLoc;
1163 /// The location of the restrict-qualifier, if any.
1164 unsigned RestrictQualLoc;
1166 /// The location of the _Atomic-qualifier, if any.
1167 unsigned AtomicQualLoc;
1169 /// The location of the __unaligned-qualifier, if any.
1170 unsigned UnalignedQualLoc;
1176 struct ReferenceTypeInfo : TypeInfoCommon {
1177 /// The type qualifier: restrict. [GNU] C++ extension
1178 bool HasRestrict : 1;
1179 /// True if this is an lvalue reference, false if it's an rvalue reference.
1185 struct ArrayTypeInfo : TypeInfoCommon {
1186 /// The type qualifiers for the array:
1187 /// const/volatile/restrict/__unaligned/_Atomic.
1188 unsigned TypeQuals : 5;
1190 /// True if this dimension included the 'static' keyword.
1191 unsigned hasStatic : 1;
1193 /// True if this dimension was [*]. In this case, NumElts is null.
1194 unsigned isStar : 1;
1196 /// This is the size of the array, or null if [] or [*] was specified.
1197 /// Since the parser is multi-purpose, and we don't want to impose a root
1198 /// expression class on all clients, NumElts is untyped.
1204 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1205 /// declarator is parsed. There are two interesting styles of parameters
1207 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1208 /// lists will have information about the identifier, but no type information.
1209 /// Parameter type lists will have type info (if the actions module provides
1210 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1212 IdentifierInfo *Ident;
1213 SourceLocation IdentLoc;
1216 /// DefaultArgTokens - When the parameter's default argument
1217 /// cannot be parsed immediately (because it occurs within the
1218 /// declaration of a member function), it will be stored here as a
1219 /// sequence of tokens to be parsed once the class definition is
1220 /// complete. Non-NULL indicates that there is a default argument.
1221 std::unique_ptr<CachedTokens> DefaultArgTokens;
1223 ParamInfo() = default;
1224 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1226 std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1227 : Ident(ident), IdentLoc(iloc), Param(param),
1228 DefaultArgTokens(std::move(DefArgTokens)) {}
1231 struct TypeAndRange {
1236 struct FunctionTypeInfo : TypeInfoCommon {
1237 /// hasPrototype - This is true if the function had at least one typed
1238 /// parameter. If the function is () or (a,b,c), then it has no prototype,
1239 /// and is treated as a K&R-style function.
1240 unsigned hasPrototype : 1;
1242 /// isVariadic - If this function has a prototype, and if that
1243 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1244 /// contains the location of the ellipsis.
1245 unsigned isVariadic : 1;
1247 /// Can this declaration be a constructor-style initializer?
1248 unsigned isAmbiguous : 1;
1250 /// \brief Whether the ref-qualifier (if any) is an lvalue reference.
1251 /// Otherwise, it's an rvalue reference.
1252 unsigned RefQualifierIsLValueRef : 1;
1254 /// The type qualifiers: const/volatile/restrict/__unaligned
1255 /// The qualifier bitmask values are the same as in QualType.
1256 unsigned TypeQuals : 4;
1258 /// ExceptionSpecType - An ExceptionSpecificationType value.
1259 unsigned ExceptionSpecType : 4;
1261 /// DeleteParams - If this is true, we need to delete[] Params.
1262 unsigned DeleteParams : 1;
1264 /// HasTrailingReturnType - If this is true, a trailing return type was
1266 unsigned HasTrailingReturnType : 1;
1268 /// The location of the left parenthesis in the source.
1271 /// When isVariadic is true, the location of the ellipsis in the source.
1272 unsigned EllipsisLoc;
1274 /// The location of the right parenthesis in the source.
1277 /// NumParams - This is the number of formal parameters specified by the
1281 /// NumExceptionsOrDecls - This is the number of types in the
1282 /// dynamic-exception-decl, if the function has one. In C, this is the
1283 /// number of declarations in the function prototype.
1284 unsigned NumExceptionsOrDecls;
1286 /// \brief The location of the ref-qualifier, if any.
1288 /// If this is an invalid location, there is no ref-qualifier.
1289 unsigned RefQualifierLoc;
1291 /// \brief The location of the const-qualifier, if any.
1293 /// If this is an invalid location, there is no const-qualifier.
1294 unsigned ConstQualifierLoc;
1296 /// \brief The location of the volatile-qualifier, if any.
1298 /// If this is an invalid location, there is no volatile-qualifier.
1299 unsigned VolatileQualifierLoc;
1301 /// \brief The location of the restrict-qualifier, if any.
1303 /// If this is an invalid location, there is no restrict-qualifier.
1304 unsigned RestrictQualifierLoc;
1306 /// \brief The location of the 'mutable' qualifer in a lambda-declarator, if
1308 unsigned MutableLoc;
1310 /// \brief The beginning location of the exception specification, if any.
1311 unsigned ExceptionSpecLocBeg;
1313 /// \brief The end location of the exception specification, if any.
1314 unsigned ExceptionSpecLocEnd;
1316 /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1317 /// describe the parameters specified by this function declarator. null if
1318 /// there are no parameters specified.
1322 /// \brief Pointer to a new[]'d array of TypeAndRange objects that
1323 /// contain the types in the function's dynamic exception specification
1324 /// and their locations, if there is one.
1325 TypeAndRange *Exceptions;
1327 /// \brief Pointer to the expression in the noexcept-specifier of this
1328 /// function, if it has one.
1331 /// \brief Pointer to the cached tokens for an exception-specification
1332 /// that has not yet been parsed.
1333 CachedTokens *ExceptionSpecTokens;
1335 /// Pointer to a new[]'d array of declarations that need to be available
1336 /// for lookup inside the function body, if one exists. Does not exist in
1338 NamedDecl **DeclsInPrototype;
1341 /// \brief If HasTrailingReturnType is true, this is the trailing return
1343 UnionParsedType TrailingReturnType;
1345 /// \brief Reset the parameter list to having zero parameters.
1347 /// This is used in various places for error recovery.
1349 for (unsigned I = 0; I < NumParams; ++I)
1350 Params[I].DefaultArgTokens.reset();
1353 DeleteParams = false;
1361 switch (getExceptionSpecType()) {
1365 delete[] Exceptions;
1368 delete ExceptionSpecTokens;
1371 if (NumExceptionsOrDecls != 0)
1372 delete[] DeclsInPrototype;
1377 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1378 /// like "void foo(a,b,c)". In a function definition, this will be followed
1379 /// by the parameter type definitions.
1380 bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1382 SourceLocation getLParenLoc() const {
1383 return SourceLocation::getFromRawEncoding(LParenLoc);
1386 SourceLocation getEllipsisLoc() const {
1387 return SourceLocation::getFromRawEncoding(EllipsisLoc);
1390 SourceLocation getRParenLoc() const {
1391 return SourceLocation::getFromRawEncoding(RParenLoc);
1394 SourceLocation getExceptionSpecLocBeg() const {
1395 return SourceLocation::getFromRawEncoding(ExceptionSpecLocBeg);
1398 SourceLocation getExceptionSpecLocEnd() const {
1399 return SourceLocation::getFromRawEncoding(ExceptionSpecLocEnd);
1402 SourceRange getExceptionSpecRange() const {
1403 return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1406 /// \brief Retrieve the location of the ref-qualifier, if any.
1407 SourceLocation getRefQualifierLoc() const {
1408 return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1411 /// \brief Retrieve the location of the 'const' qualifier, if any.
1412 SourceLocation getConstQualifierLoc() const {
1413 return SourceLocation::getFromRawEncoding(ConstQualifierLoc);
1416 /// \brief Retrieve the location of the 'volatile' qualifier, if any.
1417 SourceLocation getVolatileQualifierLoc() const {
1418 return SourceLocation::getFromRawEncoding(VolatileQualifierLoc);
1421 /// \brief Retrieve the location of the 'restrict' qualifier, if any.
1422 SourceLocation getRestrictQualifierLoc() const {
1423 return SourceLocation::getFromRawEncoding(RestrictQualifierLoc);
1426 /// \brief Retrieve the location of the 'mutable' qualifier, if any.
1427 SourceLocation getMutableLoc() const {
1428 return SourceLocation::getFromRawEncoding(MutableLoc);
1431 /// \brief Determine whether this function declaration contains a
1433 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1435 /// \brief Determine whether this lambda-declarator contains a 'mutable'
1437 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1439 /// \brief Get the type of exception specification this function has.
1440 ExceptionSpecificationType getExceptionSpecType() const {
1441 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1444 /// \brief Get the number of dynamic exception specifications.
1445 unsigned getNumExceptions() const {
1446 assert(ExceptionSpecType != EST_None);
1447 return NumExceptionsOrDecls;
1450 /// \brief Get the non-parameter decls defined within this function
1451 /// prototype. Typically these are tag declarations.
1452 ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1453 assert(ExceptionSpecType == EST_None);
1454 return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1457 /// \brief Determine whether this function declarator had a
1458 /// trailing-return-type.
1459 bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1461 /// \brief Get the trailing-return-type for this function declarator.
1462 ParsedType getTrailingReturnType() const { return TrailingReturnType; }
1465 struct BlockPointerTypeInfo : TypeInfoCommon {
1466 /// For now, sema will catch these as invalid.
1467 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1468 unsigned TypeQuals : 5;
1474 struct MemberPointerTypeInfo : TypeInfoCommon {
1475 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1476 unsigned TypeQuals : 5;
1477 // CXXScopeSpec has a constructor, so it can't be a direct member.
1478 // So we need some pointer-aligned storage and a bit of trickery.
1479 alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1480 CXXScopeSpec &Scope() {
1481 return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1483 const CXXScopeSpec &Scope() const {
1484 return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1487 Scope().~CXXScopeSpec();
1491 struct PipeTypeInfo : TypeInfoCommon {
1492 /// The access writes.
1493 unsigned AccessWrites : 3;
1499 TypeInfoCommon Common;
1500 PointerTypeInfo Ptr;
1501 ReferenceTypeInfo Ref;
1503 FunctionTypeInfo Fun;
1504 BlockPointerTypeInfo Cls;
1505 MemberPointerTypeInfo Mem;
1506 PipeTypeInfo PipeInfo;
1511 case DeclaratorChunk::Function: return Fun.destroy();
1512 case DeclaratorChunk::Pointer: return Ptr.destroy();
1513 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1514 case DeclaratorChunk::Reference: return Ref.destroy();
1515 case DeclaratorChunk::Array: return Arr.destroy();
1516 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1517 case DeclaratorChunk::Paren: return;
1518 case DeclaratorChunk::Pipe: return PipeInfo.destroy();
1522 /// \brief If there are attributes applied to this declaratorchunk, return
1524 const AttributeList *getAttrs() const {
1525 return Common.AttrList;
1528 AttributeList *&getAttrListRef() {
1529 return Common.AttrList;
1532 /// \brief Return a DeclaratorChunk for a pointer.
1533 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1534 SourceLocation ConstQualLoc,
1535 SourceLocation VolatileQualLoc,
1536 SourceLocation RestrictQualLoc,
1537 SourceLocation AtomicQualLoc,
1538 SourceLocation UnalignedQualLoc) {
1542 I.Ptr.TypeQuals = TypeQuals;
1543 I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding();
1544 I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1545 I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1546 I.Ptr.AtomicQualLoc = AtomicQualLoc.getRawEncoding();
1547 I.Ptr.UnalignedQualLoc = UnalignedQualLoc.getRawEncoding();
1548 I.Ptr.AttrList = nullptr;
1552 /// \brief Return a DeclaratorChunk for a reference.
1553 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1558 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1559 I.Ref.LValueRef = lvalue;
1560 I.Ref.AttrList = nullptr;
1564 /// \brief Return a DeclaratorChunk for an array.
1565 static DeclaratorChunk getArray(unsigned TypeQuals,
1566 bool isStatic, bool isStar, Expr *NumElts,
1567 SourceLocation LBLoc, SourceLocation RBLoc) {
1572 I.Arr.AttrList = nullptr;
1573 I.Arr.TypeQuals = TypeQuals;
1574 I.Arr.hasStatic = isStatic;
1575 I.Arr.isStar = isStar;
1576 I.Arr.NumElts = NumElts;
1580 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1581 /// "TheDeclarator" is the declarator that this will be added to.
1582 static DeclaratorChunk getFunction(bool HasProto,
1584 SourceLocation LParenLoc,
1585 ParamInfo *Params, unsigned NumParams,
1586 SourceLocation EllipsisLoc,
1587 SourceLocation RParenLoc,
1589 bool RefQualifierIsLvalueRef,
1590 SourceLocation RefQualifierLoc,
1591 SourceLocation ConstQualifierLoc,
1592 SourceLocation VolatileQualifierLoc,
1593 SourceLocation RestrictQualifierLoc,
1594 SourceLocation MutableLoc,
1595 ExceptionSpecificationType ESpecType,
1596 SourceRange ESpecRange,
1597 ParsedType *Exceptions,
1598 SourceRange *ExceptionRanges,
1599 unsigned NumExceptions,
1601 CachedTokens *ExceptionSpecTokens,
1602 ArrayRef<NamedDecl *> DeclsInPrototype,
1603 SourceLocation LocalRangeBegin,
1604 SourceLocation LocalRangeEnd,
1605 Declarator &TheDeclarator,
1606 TypeResult TrailingReturnType =
1609 /// \brief Return a DeclaratorChunk for a block.
1610 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1611 SourceLocation Loc) {
1613 I.Kind = BlockPointer;
1615 I.Cls.TypeQuals = TypeQuals;
1616 I.Cls.AttrList = nullptr;
1620 /// \brief Return a DeclaratorChunk for a block.
1621 static DeclaratorChunk getPipe(unsigned TypeQuals,
1622 SourceLocation Loc) {
1626 I.Cls.TypeQuals = TypeQuals;
1627 I.Cls.AttrList = nullptr;
1631 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1633 SourceLocation Loc) {
1635 I.Kind = MemberPointer;
1636 I.Loc = SS.getBeginLoc();
1638 I.Mem.TypeQuals = TypeQuals;
1639 I.Mem.AttrList = nullptr;
1640 new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1644 /// \brief Return a DeclaratorChunk for a paren.
1645 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1646 SourceLocation RParenLoc) {
1650 I.EndLoc = RParenLoc;
1651 I.Common.AttrList = nullptr;
1655 bool isParen() const {
1656 return Kind == Paren;
1660 /// A parsed C++17 decomposition declarator of the form
1661 /// '[' identifier-list ']'
1662 class DecompositionDeclarator {
1665 IdentifierInfo *Name;
1666 SourceLocation NameLoc;
1670 /// The locations of the '[' and ']' tokens.
1671 SourceLocation LSquareLoc, RSquareLoc;
1675 unsigned NumBindings : 31;
1676 unsigned DeleteBindings : 1;
1678 friend class Declarator;
1681 DecompositionDeclarator()
1682 : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1683 DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1684 DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1685 ~DecompositionDeclarator() {
1691 LSquareLoc = RSquareLoc = SourceLocation();
1696 DeleteBindings = false;
1699 ArrayRef<Binding> bindings() const {
1700 return llvm::makeArrayRef(Bindings, NumBindings);
1703 bool isSet() const { return LSquareLoc.isValid(); }
1705 SourceLocation getLSquareLoc() const { return LSquareLoc; }
1706 SourceLocation getRSquareLoc() const { return RSquareLoc; }
1707 SourceRange getSourceRange() const {
1708 return SourceRange(LSquareLoc, RSquareLoc);
1712 /// \brief Described the kind of function definition (if any) provided for
1714 enum FunctionDefinitionKind {
1721 /// \brief Information about one declarator, including the parsed type
1722 /// information and the identifier.
1724 /// When the declarator is fully formed, this is turned into the appropriate
1727 /// Declarators come in two types: normal declarators and abstract declarators.
1728 /// Abstract declarators are used when parsing types, and don't have an
1729 /// identifier. Normal declarators do have ID's.
1731 /// Instances of this class should be a transient object that lives on the
1732 /// stack, not objects that are allocated in large quantities on the heap.
1736 FileContext, // File scope declaration.
1737 PrototypeContext, // Within a function prototype.
1738 ObjCResultContext, // An ObjC method result type.
1739 ObjCParameterContext,// An ObjC method parameter type.
1740 KNRTypeListContext, // K&R type definition list for formals.
1741 TypeNameContext, // Abstract declarator for types.
1742 FunctionalCastContext, // Type in a C++ functional cast expression.
1743 MemberContext, // Struct/Union field.
1744 BlockContext, // Declaration within a block in a function.
1745 ForContext, // Declaration within first part of a for loop.
1746 InitStmtContext, // Declaration within optional init stmt of if/switch.
1747 ConditionContext, // Condition declaration in a C++ if/switch/while/for.
1748 TemplateParamContext,// Within a template parameter list.
1749 CXXNewContext, // C++ new-expression.
1750 CXXCatchContext, // C++ catch exception-declaration
1751 ObjCCatchContext, // Objective-C catch exception-declaration
1752 BlockLiteralContext, // Block literal declarator.
1753 LambdaExprContext, // Lambda-expression declarator.
1754 LambdaExprParameterContext, // Lambda-expression parameter declarator.
1755 ConversionIdContext, // C++ conversion-type-id.
1756 TrailingReturnContext, // C++11 trailing-type-specifier.
1757 TemplateTypeArgContext, // Template type argument.
1758 AliasDeclContext, // C++11 alias-declaration.
1759 AliasTemplateContext // C++11 alias-declaration template.
1768 /// \brief Where we are parsing this declarator.
1771 /// The C++17 structured binding, if any. This is an alternative to a Name.
1772 DecompositionDeclarator BindingGroup;
1774 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1775 /// parsed. This is pushed from the identifier out, which means that element
1776 /// #0 will be the most closely bound to the identifier, and
1777 /// DeclTypeInfo.back() will be the least closely bound.
1778 SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1780 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1781 unsigned InvalidType : 1;
1783 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1784 unsigned GroupingParens : 1;
1786 /// FunctionDefinition - Is this Declarator for a function or member
1787 /// definition and, if so, what kind?
1789 /// Actually a FunctionDefinitionKind.
1790 unsigned FunctionDefinition : 2;
1792 /// \brief Is this Declarator a redeclaration?
1793 unsigned Redeclaration : 1;
1795 /// \brief true if the declaration is preceded by \c __extension__.
1796 unsigned Extension : 1;
1798 /// Indicates whether this is an Objective-C instance variable.
1799 unsigned ObjCIvar : 1;
1801 /// Indicates whether this is an Objective-C 'weak' property.
1802 unsigned ObjCWeakProperty : 1;
1804 /// Indicates whether the InlineParams / InlineBindings storage has been used.
1805 unsigned InlineStorageUsed : 1;
1807 /// Attrs - Attributes.
1808 ParsedAttributes Attrs;
1810 /// \brief The asm label, if specified.
1816 /// InlineParams - This is a local array used for the first function decl
1817 /// chunk to avoid going to the heap for the common case when we have one
1818 /// function chunk in the declarator.
1819 DeclaratorChunk::ParamInfo InlineParams[16];
1820 DecompositionDeclarator::Binding InlineBindings[16];
1825 /// \brief If this is the second or subsequent declarator in this declaration,
1826 /// the location of the comma before this declarator.
1827 SourceLocation CommaLoc;
1829 /// \brief If provided, the source location of the ellipsis used to describe
1830 /// this declarator as a parameter pack.
1831 SourceLocation EllipsisLoc;
1833 friend struct DeclaratorChunk;
1836 Declarator(const DeclSpec &ds, TheContext C)
1837 : DS(ds), Range(ds.getSourceRange()), Context(C),
1838 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1839 GroupingParens(false), FunctionDefinition(FDK_Declaration),
1840 Redeclaration(false), Extension(false), ObjCIvar(false),
1841 ObjCWeakProperty(false), InlineStorageUsed(false),
1842 Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr) {}
1847 /// getDeclSpec - Return the declaration-specifier that this declarator was
1849 const DeclSpec &getDeclSpec() const { return DS; }
1851 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1852 /// should be used with extreme care: declspecs can often be shared between
1853 /// multiple declarators, so mutating the DeclSpec affects all of the
1854 /// Declarators. This should only be done when the declspec is known to not
1855 /// be shared or when in error recovery etc.
1856 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1858 AttributePool &getAttributePool() const {
1859 return Attrs.getPool();
1862 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1863 /// nested-name-specifier) that is part of the declarator-id.
1864 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1865 CXXScopeSpec &getCXXScopeSpec() { return SS; }
1867 /// \brief Retrieve the name specified by this declarator.
1868 UnqualifiedId &getName() { return Name; }
1870 const DecompositionDeclarator &getDecompositionDeclarator() const {
1871 return BindingGroup;
1874 TheContext getContext() const { return Context; }
1876 bool isPrototypeContext() const {
1877 return (Context == PrototypeContext ||
1878 Context == ObjCParameterContext ||
1879 Context == ObjCResultContext ||
1880 Context == LambdaExprParameterContext);
1883 /// \brief Get the source range that spans this declarator.
1884 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1885 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1886 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1888 void SetSourceRange(SourceRange R) { Range = R; }
1889 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1891 void SetRangeBegin(SourceLocation Loc) {
1892 if (!Loc.isInvalid())
1893 Range.setBegin(Loc);
1895 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1896 void SetRangeEnd(SourceLocation Loc) {
1897 if (!Loc.isInvalid())
1900 /// ExtendWithDeclSpec - Extend the declarator source range to include the
1901 /// given declspec, unless its location is invalid. Adopts the range start if
1902 /// the current range start is invalid.
1903 void ExtendWithDeclSpec(const DeclSpec &DS) {
1904 SourceRange SR = DS.getSourceRange();
1905 if (Range.getBegin().isInvalid())
1906 Range.setBegin(SR.getBegin());
1907 if (!SR.getEnd().isInvalid())
1908 Range.setEnd(SR.getEnd());
1911 /// \brief Reset the contents of this Declarator.
1915 Range = DS.getSourceRange();
1916 BindingGroup.clear();
1918 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1919 DeclTypeInfo[i].destroy();
1920 DeclTypeInfo.clear();
1923 InlineStorageUsed = false;
1925 ObjCWeakProperty = false;
1926 CommaLoc = SourceLocation();
1927 EllipsisLoc = SourceLocation();
1930 /// mayOmitIdentifier - Return true if the identifier is either optional or
1931 /// not allowed. This is true for typenames, prototypes, and template
1932 /// parameter lists.
1933 bool mayOmitIdentifier() const {
1936 case KNRTypeListContext:
1940 case InitStmtContext:
1941 case ConditionContext:
1944 case TypeNameContext:
1945 case FunctionalCastContext:
1946 case AliasDeclContext:
1947 case AliasTemplateContext:
1948 case PrototypeContext:
1949 case LambdaExprParameterContext:
1950 case ObjCParameterContext:
1951 case ObjCResultContext:
1952 case TemplateParamContext:
1954 case CXXCatchContext:
1955 case ObjCCatchContext:
1956 case BlockLiteralContext:
1957 case LambdaExprContext:
1958 case ConversionIdContext:
1959 case TemplateTypeArgContext:
1960 case TrailingReturnContext:
1963 llvm_unreachable("unknown context kind!");
1966 /// mayHaveIdentifier - Return true if the identifier is either optional or
1967 /// required. This is true for normal declarators and prototypes, but not
1969 bool mayHaveIdentifier() const {
1972 case KNRTypeListContext:
1976 case InitStmtContext:
1977 case ConditionContext:
1978 case PrototypeContext:
1979 case LambdaExprParameterContext:
1980 case TemplateParamContext:
1981 case CXXCatchContext:
1982 case ObjCCatchContext:
1985 case TypeNameContext:
1986 case FunctionalCastContext:
1988 case AliasDeclContext:
1989 case AliasTemplateContext:
1990 case ObjCParameterContext:
1991 case ObjCResultContext:
1992 case BlockLiteralContext:
1993 case LambdaExprContext:
1994 case ConversionIdContext:
1995 case TemplateTypeArgContext:
1996 case TrailingReturnContext:
1999 llvm_unreachable("unknown context kind!");
2002 /// diagnoseIdentifier - Return true if the identifier is prohibited and
2003 /// should be diagnosed (because it cannot be anything else).
2004 bool diagnoseIdentifier() const {
2007 case KNRTypeListContext:
2011 case InitStmtContext:
2012 case ConditionContext:
2013 case PrototypeContext:
2014 case LambdaExprParameterContext:
2015 case TemplateParamContext:
2016 case CXXCatchContext:
2017 case ObjCCatchContext:
2018 case TypeNameContext:
2019 case FunctionalCastContext:
2020 case ConversionIdContext:
2021 case ObjCParameterContext:
2022 case ObjCResultContext:
2023 case BlockLiteralContext:
2025 case LambdaExprContext:
2028 case AliasDeclContext:
2029 case AliasTemplateContext:
2030 case TemplateTypeArgContext:
2031 case TrailingReturnContext:
2034 llvm_unreachable("unknown context kind!");
2037 /// Return true if the context permits a C++17 decomposition declarator.
2038 bool mayHaveDecompositionDeclarator() const {
2041 // FIXME: It's not clear that the proposal meant to allow file-scope
2042 // structured bindings, but it does.
2045 case InitStmtContext:
2048 case ConditionContext:
2050 case PrototypeContext:
2051 case TemplateParamContext:
2055 // These contexts don't allow any kind of non-abstract declarator.
2056 case KNRTypeListContext:
2057 case TypeNameContext:
2058 case FunctionalCastContext:
2059 case AliasDeclContext:
2060 case AliasTemplateContext:
2061 case LambdaExprParameterContext:
2062 case ObjCParameterContext:
2063 case ObjCResultContext:
2065 case CXXCatchContext:
2066 case ObjCCatchContext:
2067 case BlockLiteralContext:
2068 case LambdaExprContext:
2069 case ConversionIdContext:
2070 case TemplateTypeArgContext:
2071 case TrailingReturnContext:
2074 llvm_unreachable("unknown context kind!");
2077 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2078 /// followed by a C++ direct initializer, e.g. "int x(1);".
2079 bool mayBeFollowedByCXXDirectInit() const {
2080 if (hasGroupingParens()) return false;
2082 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2085 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2086 Context != FileContext)
2089 // Special names can't have direct initializers.
2090 if (Name.getKind() != UnqualifiedId::IK_Identifier)
2097 case InitStmtContext:
2100 case ConditionContext:
2101 // This may not be followed by a direct initializer, but it can't be a
2102 // function declaration either, and we'd prefer to perform a tentative
2103 // parse in order to produce the right diagnostic.
2106 case KNRTypeListContext:
2108 case PrototypeContext:
2109 case LambdaExprParameterContext:
2110 case ObjCParameterContext:
2111 case ObjCResultContext:
2112 case TemplateParamContext:
2113 case CXXCatchContext:
2114 case ObjCCatchContext:
2115 case TypeNameContext:
2116 case FunctionalCastContext: // FIXME
2118 case AliasDeclContext:
2119 case AliasTemplateContext:
2120 case BlockLiteralContext:
2121 case LambdaExprContext:
2122 case ConversionIdContext:
2123 case TemplateTypeArgContext:
2124 case TrailingReturnContext:
2127 llvm_unreachable("unknown context kind!");
2130 /// isPastIdentifier - Return true if we have parsed beyond the point where
2131 /// the name would appear. (This may happen even if we haven't actually parsed
2132 /// a name, perhaps because this context doesn't require one.)
2133 bool isPastIdentifier() const { return Name.isValid(); }
2135 /// hasName - Whether this declarator has a name, which might be an
2136 /// identifier (accessible via getIdentifier()) or some kind of
2137 /// special C++ name (constructor, destructor, etc.), or a structured
2138 /// binding (which is not exactly a name, but occupies the same position).
2139 bool hasName() const {
2140 return Name.getKind() != UnqualifiedId::IK_Identifier || Name.Identifier ||
2141 isDecompositionDeclarator();
2144 /// Return whether this declarator is a decomposition declarator.
2145 bool isDecompositionDeclarator() const {
2146 return BindingGroup.isSet();
2149 IdentifierInfo *getIdentifier() const {
2150 if (Name.getKind() == UnqualifiedId::IK_Identifier)
2151 return Name.Identifier;
2155 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2157 /// \brief Set the name of this declarator to be the given identifier.
2158 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2159 Name.setIdentifier(Id, IdLoc);
2162 /// Set the decomposition bindings for this declarator.
2164 setDecompositionBindings(SourceLocation LSquareLoc,
2165 ArrayRef<DecompositionDeclarator::Binding> Bindings,
2166 SourceLocation RSquareLoc);
2168 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2169 /// EndLoc, which should be the last token of the chunk.
2170 void AddTypeInfo(const DeclaratorChunk &TI,
2171 ParsedAttributes &attrs,
2172 SourceLocation EndLoc) {
2173 DeclTypeInfo.push_back(TI);
2174 DeclTypeInfo.back().getAttrListRef() = attrs.getList();
2175 getAttributePool().takeAllFrom(attrs.getPool());
2177 if (!EndLoc.isInvalid())
2178 SetRangeEnd(EndLoc);
2181 /// \brief Add a new innermost chunk to this declarator.
2182 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2183 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2186 /// \brief Return the number of types applied to this declarator.
2187 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2189 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
2190 /// closest to the identifier.
2191 const DeclaratorChunk &getTypeObject(unsigned i) const {
2192 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2193 return DeclTypeInfo[i];
2195 DeclaratorChunk &getTypeObject(unsigned i) {
2196 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2197 return DeclTypeInfo[i];
2200 typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2201 typedef llvm::iterator_range<type_object_iterator> type_object_range;
2203 /// Returns the range of type objects, from the identifier outwards.
2204 type_object_range type_objects() const {
2205 return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2208 void DropFirstTypeObject() {
2209 assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
2210 DeclTypeInfo.front().destroy();
2211 DeclTypeInfo.erase(DeclTypeInfo.begin());
2214 /// Return the innermost (closest to the declarator) chunk of this
2215 /// declarator that is not a parens chunk, or null if there are no
2216 /// non-parens chunks.
2217 const DeclaratorChunk *getInnermostNonParenChunk() const {
2218 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2219 if (!DeclTypeInfo[i].isParen())
2220 return &DeclTypeInfo[i];
2225 /// Return the outermost (furthest from the declarator) chunk of
2226 /// this declarator that is not a parens chunk, or null if there are
2227 /// no non-parens chunks.
2228 const DeclaratorChunk *getOutermostNonParenChunk() const {
2229 for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2230 if (!DeclTypeInfo[i-1].isParen())
2231 return &DeclTypeInfo[i-1];
2236 /// isArrayOfUnknownBound - This method returns true if the declarator
2237 /// is a declarator for an array of unknown bound (looking through
2239 bool isArrayOfUnknownBound() const {
2240 const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2241 return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2242 !chunk->Arr.NumElts);
2245 /// isFunctionDeclarator - This method returns true if the declarator
2246 /// is a function declarator (looking through parentheses).
2247 /// If true is returned, then the reference type parameter idx is
2248 /// assigned with the index of the declaration chunk.
2249 bool isFunctionDeclarator(unsigned& idx) const {
2250 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2251 switch (DeclTypeInfo[i].Kind) {
2252 case DeclaratorChunk::Function:
2255 case DeclaratorChunk::Paren:
2257 case DeclaratorChunk::Pointer:
2258 case DeclaratorChunk::Reference:
2259 case DeclaratorChunk::Array:
2260 case DeclaratorChunk::BlockPointer:
2261 case DeclaratorChunk::MemberPointer:
2262 case DeclaratorChunk::Pipe:
2265 llvm_unreachable("Invalid type chunk");
2270 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2271 /// this method returns true if the identifier is a function declarator
2272 /// (looking through parentheses).
2273 bool isFunctionDeclarator() const {
2275 return isFunctionDeclarator(index);
2278 /// getFunctionTypeInfo - Retrieves the function type info object
2279 /// (looking through parentheses).
2280 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2281 assert(isFunctionDeclarator() && "Not a function declarator!");
2283 isFunctionDeclarator(index);
2284 return DeclTypeInfo[index].Fun;
2287 /// getFunctionTypeInfo - Retrieves the function type info object
2288 /// (looking through parentheses).
2289 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2290 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2293 /// \brief Determine whether the declaration that will be produced from
2294 /// this declaration will be a function.
2296 /// A declaration can declare a function even if the declarator itself
2297 /// isn't a function declarator, if the type specifier refers to a function
2298 /// type. This routine checks for both cases.
2299 bool isDeclarationOfFunction() const;
2301 /// \brief Return true if this declaration appears in a context where a
2302 /// function declarator would be a function declaration.
2303 bool isFunctionDeclarationContext() const {
2304 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2312 case InitStmtContext:
2315 case ConditionContext:
2316 case KNRTypeListContext:
2317 case TypeNameContext:
2318 case FunctionalCastContext:
2319 case AliasDeclContext:
2320 case AliasTemplateContext:
2321 case PrototypeContext:
2322 case LambdaExprParameterContext:
2323 case ObjCParameterContext:
2324 case ObjCResultContext:
2325 case TemplateParamContext:
2327 case CXXCatchContext:
2328 case ObjCCatchContext:
2329 case BlockLiteralContext:
2330 case LambdaExprContext:
2331 case ConversionIdContext:
2332 case TemplateTypeArgContext:
2333 case TrailingReturnContext:
2336 llvm_unreachable("unknown context kind!");
2339 /// \brief Return true if a function declarator at this position would be a
2340 /// function declaration.
2341 bool isFunctionDeclaratorAFunctionDeclaration() const {
2342 if (!isFunctionDeclarationContext())
2345 for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2346 if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2352 /// \brief Determine whether a trailing return type was written (at any
2353 /// level) within this declarator.
2354 bool hasTrailingReturnType() const {
2355 for (const auto &Chunk : type_objects())
2356 if (Chunk.Kind == DeclaratorChunk::Function &&
2357 Chunk.Fun.hasTrailingReturnType())
2362 /// takeAttributes - Takes attributes from the given parsed-attributes
2363 /// set and add them to this declarator.
2365 /// These examples both add 3 attributes to "var":
2366 /// short int var __attribute__((aligned(16),common,deprecated));
2367 /// short int x, __attribute__((aligned(16)) var
2368 /// __attribute__((common,deprecated));
2370 /// Also extends the range of the declarator.
2371 void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2372 Attrs.takeAllFrom(attrs);
2374 if (!lastLoc.isInvalid())
2375 SetRangeEnd(lastLoc);
2378 const AttributeList *getAttributes() const { return Attrs.getList(); }
2379 AttributeList *getAttributes() { return Attrs.getList(); }
2381 AttributeList *&getAttrListRef() { return Attrs.getListRef(); }
2383 /// hasAttributes - do we contain any attributes?
2384 bool hasAttributes() const {
2385 if (getAttributes() || getDeclSpec().hasAttributes()) return true;
2386 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2387 if (getTypeObject(i).getAttrs())
2392 /// \brief Return a source range list of C++11 attributes associated
2393 /// with the declarator.
2394 void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2395 AttributeList *AttrList = Attrs.getList();
2397 if (AttrList->isCXX11Attribute())
2398 Ranges.push_back(AttrList->getRange());
2399 AttrList = AttrList->getNext();
2403 void setAsmLabel(Expr *E) { AsmLabel = E; }
2404 Expr *getAsmLabel() const { return AsmLabel; }
2406 void setExtension(bool Val = true) { Extension = Val; }
2407 bool getExtension() const { return Extension; }
2409 void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2410 bool isObjCIvar() const { return ObjCIvar; }
2412 void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2413 bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2415 void setInvalidType(bool Val = true) { InvalidType = Val; }
2416 bool isInvalidType() const {
2417 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2420 void setGroupingParens(bool flag) { GroupingParens = flag; }
2421 bool hasGroupingParens() const { return GroupingParens; }
2423 bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2424 SourceLocation getCommaLoc() const { return CommaLoc; }
2425 void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2427 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2428 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2429 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2431 void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2432 FunctionDefinition = Val;
2435 bool isFunctionDefinition() const {
2436 return getFunctionDefinitionKind() != FDK_Declaration;
2439 FunctionDefinitionKind getFunctionDefinitionKind() const {
2440 return (FunctionDefinitionKind)FunctionDefinition;
2443 /// Returns true if this declares a real member and not a friend.
2444 bool isFirstDeclarationOfMember() {
2445 return getContext() == MemberContext && !getDeclSpec().isFriendSpecified();
2448 /// Returns true if this declares a static member. This cannot be called on a
2449 /// declarator outside of a MemberContext because we won't know until
2450 /// redeclaration time if the decl is static.
2451 bool isStaticMember();
2453 /// Returns true if this declares a constructor or a destructor.
2454 bool isCtorOrDtor();
2456 void setRedeclaration(bool Val) { Redeclaration = Val; }
2457 bool isRedeclaration() const { return Redeclaration; }
2460 /// \brief This little struct is used to capture information about
2461 /// structure field declarators, which is basically just a bitfield size.
2462 struct FieldDeclarator {
2465 explicit FieldDeclarator(const DeclSpec &DS)
2466 : D(DS, Declarator::MemberContext), BitfieldSize(nullptr) { }
2469 /// \brief Represents a C++11 virt-specifier-seq.
2470 class VirtSpecifiers {
2477 // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2481 VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2483 bool SetSpecifier(Specifier VS, SourceLocation Loc,
2484 const char *&PrevSpec);
2486 bool isUnset() const { return Specifiers == 0; }
2488 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2489 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2491 bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2492 bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2493 SourceLocation getFinalLoc() const { return VS_finalLoc; }
2495 void clear() { Specifiers = 0; }
2497 static const char *getSpecifierName(Specifier VS);
2499 SourceLocation getFirstLocation() const { return FirstLocation; }
2500 SourceLocation getLastLocation() const { return LastLocation; }
2501 Specifier getLastSpecifier() const { return LastSpecifier; }
2504 unsigned Specifiers;
2505 Specifier LastSpecifier;
2507 SourceLocation VS_overrideLoc, VS_finalLoc;
2508 SourceLocation FirstLocation;
2509 SourceLocation LastLocation;
2512 enum class LambdaCaptureInitKind {
2514 CopyInit, //!< [a = b], [a = {b}]
2515 DirectInit, //!< [a(b)]
2516 ListInit //!< [a{b}]
2519 /// \brief Represents a complete lambda introducer.
2520 struct LambdaIntroducer {
2521 /// \brief An individual capture in a lambda introducer.
2522 struct LambdaCapture {
2523 LambdaCaptureKind Kind;
2526 SourceLocation EllipsisLoc;
2527 LambdaCaptureInitKind InitKind;
2529 ParsedType InitCaptureType;
2530 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2531 IdentifierInfo *Id, SourceLocation EllipsisLoc,
2532 LambdaCaptureInitKind InitKind, ExprResult Init,
2533 ParsedType InitCaptureType)
2534 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2535 InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType) {}
2539 SourceLocation DefaultLoc;
2540 LambdaCaptureDefault Default;
2541 SmallVector<LambdaCapture, 4> Captures;
2544 : Default(LCD_None) {}
2546 /// \brief Append a capture in a lambda introducer.
2547 void addCapture(LambdaCaptureKind Kind,
2550 SourceLocation EllipsisLoc,
2551 LambdaCaptureInitKind InitKind,
2553 ParsedType InitCaptureType) {
2554 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2559 } // end namespace clang
2561 #endif // LLVM_CLANG_SEMA_DECLSPEC_H