1 //===--- DeclSpec.h - Parsed declaration specifiers -------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// This file defines the classes used to store parsed information about
11 /// declaration-specifiers and declarators.
14 /// static const int volatile x, *y, *(*(*z)[10])(const void *x);
15 /// ------------------------- - -- ---------------------------
16 /// declaration-specifiers \ | /
20 //===----------------------------------------------------------------------===//
22 #ifndef LLVM_CLANG_SEMA_DECLSPEC_H
23 #define LLVM_CLANG_SEMA_DECLSPEC_H
25 #include "clang/AST/DeclCXX.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/Ownership.h"
33 #include "clang/Sema/ParsedAttr.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 /// 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 /// Retrieve the representation of the nested-name-specifier.
76 NestedNameSpecifier *getScopeRep() const {
77 return Builder.getRepresentation();
80 /// 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 /// 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 /// 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 /// 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 /// Turn this (empty) nested-name-specifier into the global
138 /// nested-name-specifier '::'.
139 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
141 /// 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 /// 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 /// Adopt an existing nested-name-specifier (with source-range
168 void Adopt(NestedNameSpecifierLoc Other);
170 /// 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 /// 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 /// 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 /// Retrieve the data associated with the source-location information.
217 char *location_data() const { return Builder.getBuffer().first; }
219 /// Retrieve the size of the data associated with source-location
221 unsigned location_size() const { return Builder.getBuffer().second; }
224 /// Captures information about "declaration specifiers".
226 /// "Declaration specifiers" encompasses storage-class-specifiers,
227 /// type-specifiers, type-qualifiers, and function-specifiers.
230 /// 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_char8 = clang::TST_char8;
277 static const TST TST_char16 = clang::TST_char16;
278 static const TST TST_char32 = clang::TST_char32;
279 static const TST TST_int = clang::TST_int;
280 static const TST TST_int128 = clang::TST_int128;
281 static const TST TST_half = clang::TST_half;
282 static const TST TST_float = clang::TST_float;
283 static const TST TST_double = clang::TST_double;
284 static const TST TST_float16 = clang::TST_Float16;
285 static const TST TST_accum = clang::TST_Accum;
286 static const TST TST_fract = clang::TST_Fract;
287 static const TST TST_float128 = clang::TST_float128;
288 static const TST TST_bool = clang::TST_bool;
289 static const TST TST_decimal32 = clang::TST_decimal32;
290 static const TST TST_decimal64 = clang::TST_decimal64;
291 static const TST TST_decimal128 = clang::TST_decimal128;
292 static const TST TST_enum = clang::TST_enum;
293 static const TST TST_union = clang::TST_union;
294 static const TST TST_struct = clang::TST_struct;
295 static const TST TST_interface = clang::TST_interface;
296 static const TST TST_class = clang::TST_class;
297 static const TST TST_typename = clang::TST_typename;
298 static const TST TST_typeofType = clang::TST_typeofType;
299 static const TST TST_typeofExpr = clang::TST_typeofExpr;
300 static const TST TST_decltype = clang::TST_decltype;
301 static const TST TST_decltype_auto = clang::TST_decltype_auto;
302 static const TST TST_underlyingType = clang::TST_underlyingType;
303 static const TST TST_auto = clang::TST_auto;
304 static const TST TST_auto_type = clang::TST_auto_type;
305 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
306 static const TST TST_atomic = clang::TST_atomic;
307 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
308 static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
309 #include "clang/Basic/OpenCLImageTypes.def"
310 static const TST TST_error = clang::TST_error;
313 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
319 // This has no corresponding Qualifiers::TQ value, because it's not treated
320 // as a qualifier in our type system.
324 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
325 /// returned by getParsedSpecifiers.
326 enum ParsedSpecifiers {
328 PQ_StorageClassSpecifier = 1,
329 PQ_TypeSpecifier = 2,
330 PQ_TypeQualifier = 4,
331 PQ_FunctionSpecifier = 8
332 // FIXME: Attributes should be included here.
336 // storage-class-specifier
337 /*SCS*/unsigned StorageClassSpec : 3;
338 /*TSCS*/unsigned ThreadStorageClassSpec : 2;
339 unsigned SCS_extern_in_linkage_spec : 1;
342 /*TSW*/unsigned TypeSpecWidth : 2;
343 /*TSC*/unsigned TypeSpecComplex : 2;
344 /*TSS*/unsigned TypeSpecSign : 2;
345 /*TST*/unsigned TypeSpecType : 6;
346 unsigned TypeAltiVecVector : 1;
347 unsigned TypeAltiVecPixel : 1;
348 unsigned TypeAltiVecBool : 1;
349 unsigned TypeSpecOwned : 1;
350 unsigned TypeSpecPipe : 1;
351 unsigned TypeSpecSat : 1;
354 unsigned TypeQualifiers : 5; // Bitwise OR of TQ.
356 // function-specifier
357 unsigned FS_inline_specified : 1;
358 unsigned FS_forceinline_specified: 1;
359 unsigned FS_virtual_specified : 1;
360 unsigned FS_noreturn_specified : 1;
363 unsigned Friend_specified : 1;
365 // constexpr-specifier
366 unsigned ConstexprSpecifier : 2;
369 UnionParsedType TypeRep;
374 /// ExplicitSpecifier - Store information about explicit spicifer.
375 ExplicitSpecifier FS_explicit_specifier;
378 ParsedAttributes Attrs;
380 // Scope specifier for the type spec, if applicable.
381 CXXScopeSpec TypeScope;
383 // SourceLocation info. These are null if the item wasn't specified or if
384 // the setting was synthesized.
387 SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
388 SourceRange TSWRange;
389 SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc;
390 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
391 /// typename, then this is the location of the named type (if present);
392 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
393 /// TSTNameLoc provides source range info for tag types.
394 SourceLocation TSTNameLoc;
395 SourceRange TypeofParensRange;
396 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
398 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
399 SourceLocation FS_explicitCloseParenLoc;
400 SourceLocation FS_forceinlineLoc;
401 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
402 SourceLocation TQ_pipeLoc;
404 WrittenBuiltinSpecs writtenBS;
405 void SaveWrittenBuiltinSpecs();
407 ObjCDeclSpec *ObjCQualifiers;
409 static bool isTypeRep(TST T) {
410 return (T == TST_typename || T == TST_typeofType ||
411 T == TST_underlyingType || T == TST_atomic);
413 static bool isExprRep(TST T) {
414 return (T == TST_typeofExpr || T == TST_decltype);
417 DeclSpec(const DeclSpec &) = delete;
418 void operator=(const DeclSpec &) = delete;
420 static bool isDeclRep(TST T) {
421 return (T == TST_enum || T == TST_struct ||
422 T == TST_interface || T == TST_union ||
426 DeclSpec(AttributeFactory &attrFactory)
427 : StorageClassSpec(SCS_unspecified),
428 ThreadStorageClassSpec(TSCS_unspecified),
429 SCS_extern_in_linkage_spec(false), TypeSpecWidth(TSW_unspecified),
430 TypeSpecComplex(TSC_unspecified), TypeSpecSign(TSS_unspecified),
431 TypeSpecType(TST_unspecified), TypeAltiVecVector(false),
432 TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false),
433 TypeSpecPipe(false), TypeSpecSat(false), TypeQualifiers(TQ_unspecified),
434 FS_inline_specified(false), FS_forceinline_specified(false),
435 FS_virtual_specified(false), FS_noreturn_specified(false),
436 Friend_specified(false), ConstexprSpecifier(CSK_unspecified),
437 FS_explicit_specifier(), Attrs(attrFactory), writtenBS(),
438 ObjCQualifiers(nullptr) {}
440 // storage-class-specifier
441 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
442 TSCS getThreadStorageClassSpec() const {
443 return (TSCS)ThreadStorageClassSpec;
445 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
446 void setExternInLinkageSpec(bool Value) {
447 SCS_extern_in_linkage_spec = Value;
450 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
451 SourceLocation getThreadStorageClassSpecLoc() const {
452 return ThreadStorageClassSpecLoc;
455 void ClearStorageClassSpecs() {
456 StorageClassSpec = DeclSpec::SCS_unspecified;
457 ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
458 SCS_extern_in_linkage_spec = false;
459 StorageClassSpecLoc = SourceLocation();
460 ThreadStorageClassSpecLoc = SourceLocation();
463 void ClearTypeSpecType() {
464 TypeSpecType = DeclSpec::TST_unspecified;
465 TypeSpecOwned = false;
466 TSTLoc = SourceLocation();
470 TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
471 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
472 TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
473 TST getTypeSpecType() const { return (TST)TypeSpecType; }
474 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
475 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
476 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
477 bool isTypeSpecOwned() const { return TypeSpecOwned; }
478 bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
479 bool isTypeSpecPipe() const { return TypeSpecPipe; }
480 bool isTypeSpecSat() const { return TypeSpecSat; }
482 ParsedType getRepAsType() const {
483 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
486 Decl *getRepAsDecl() const {
487 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
490 Expr *getRepAsExpr() const {
491 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
494 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
495 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
497 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
498 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
499 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
501 SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
502 SourceRange getTypeSpecWidthRange() const { return TSWRange; }
503 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
504 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
505 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
506 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
507 SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; }
509 SourceLocation getTypeSpecTypeNameLoc() const {
510 assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename);
514 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
515 void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
517 bool hasAutoTypeSpec() const {
518 return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
519 TypeSpecType == TST_decltype_auto);
522 bool hasTagDefinition() const;
524 /// Turn a type-specifier-type into a string like "_Bool" or "union".
525 static const char *getSpecifierName(DeclSpec::TST T,
526 const PrintingPolicy &Policy);
527 static const char *getSpecifierName(DeclSpec::TQ Q);
528 static const char *getSpecifierName(DeclSpec::TSS S);
529 static const char *getSpecifierName(DeclSpec::TSC C);
530 static const char *getSpecifierName(DeclSpec::TSW W);
531 static const char *getSpecifierName(DeclSpec::SCS S);
532 static const char *getSpecifierName(DeclSpec::TSCS S);
533 static const char *getSpecifierName(ConstexprSpecKind C);
537 /// getTypeQualifiers - Return a set of TQs.
538 unsigned getTypeQualifiers() const { return TypeQualifiers; }
539 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
540 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
541 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
542 SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
543 SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
544 SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
546 /// Clear out all of the type qualifiers.
547 void ClearTypeQualifiers() {
549 TQ_constLoc = SourceLocation();
550 TQ_restrictLoc = SourceLocation();
551 TQ_volatileLoc = SourceLocation();
552 TQ_atomicLoc = SourceLocation();
553 TQ_unalignedLoc = SourceLocation();
554 TQ_pipeLoc = SourceLocation();
557 // function-specifier
558 bool isInlineSpecified() const {
559 return FS_inline_specified | FS_forceinline_specified;
561 SourceLocation getInlineSpecLoc() const {
562 return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
565 ExplicitSpecifier getExplicitSpecifier() const {
566 return FS_explicit_specifier;
569 bool isVirtualSpecified() const { return FS_virtual_specified; }
570 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
572 bool hasExplicitSpecifier() const {
573 return FS_explicit_specifier.isSpecified();
575 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
576 SourceRange getExplicitSpecRange() const {
577 return FS_explicit_specifier.getExpr()
578 ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc)
579 : SourceRange(FS_explicitLoc);
582 bool isNoreturnSpecified() const { return FS_noreturn_specified; }
583 SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
585 void ClearFunctionSpecs() {
586 FS_inline_specified = false;
587 FS_inlineLoc = SourceLocation();
588 FS_forceinline_specified = false;
589 FS_forceinlineLoc = SourceLocation();
590 FS_virtual_specified = false;
591 FS_virtualLoc = SourceLocation();
592 FS_explicit_specifier = ExplicitSpecifier();
593 FS_explicitLoc = SourceLocation();
594 FS_explicitCloseParenLoc = SourceLocation();
595 FS_noreturn_specified = false;
596 FS_noreturnLoc = SourceLocation();
599 /// This method calls the passed in handler on each CVRU qual being
601 /// Handle - a handler to be invoked.
602 void forEachCVRUQualifier(
603 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
605 /// This method calls the passed in handler on each qual being
607 /// Handle - a handler to be invoked.
608 void forEachQualifier(
609 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
611 /// Return true if any type-specifier has been found.
612 bool hasTypeSpecifier() const {
613 return getTypeSpecType() != DeclSpec::TST_unspecified ||
614 getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
615 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
616 getTypeSpecSign() != DeclSpec::TSS_unspecified;
619 /// Return a bitmask of which flavors of specifiers this
620 /// DeclSpec includes.
621 unsigned getParsedSpecifiers() const;
623 /// isEmpty - Return true if this declaration specifier is completely empty:
624 /// no tokens were parsed in the production of it.
625 bool isEmpty() const {
626 return getParsedSpecifiers() == DeclSpec::PQ_None;
629 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
630 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
632 /// These methods set the specified attribute of the DeclSpec and
633 /// return false if there was no error. If an error occurs (for
634 /// example, if we tried to set "auto" on a spec with "extern"
635 /// already set), they return true and set PrevSpec and DiagID
637 /// Diag(Loc, DiagID) << PrevSpec;
638 /// will yield a useful result.
640 /// TODO: use a more general approach that still allows these
641 /// diagnostics to be ignored when desired.
642 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
643 const char *&PrevSpec, unsigned &DiagID,
644 const PrintingPolicy &Policy);
645 bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
646 const char *&PrevSpec, unsigned &DiagID);
647 bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
648 unsigned &DiagID, const PrintingPolicy &Policy);
649 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
651 bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
653 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
654 unsigned &DiagID, const PrintingPolicy &Policy);
655 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
656 unsigned &DiagID, ParsedType Rep,
657 const PrintingPolicy &Policy);
658 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
659 unsigned &DiagID, Decl *Rep, bool Owned,
660 const PrintingPolicy &Policy);
661 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
662 SourceLocation TagNameLoc, const char *&PrevSpec,
663 unsigned &DiagID, ParsedType Rep,
664 const PrintingPolicy &Policy);
665 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
666 SourceLocation TagNameLoc, const char *&PrevSpec,
667 unsigned &DiagID, Decl *Rep, bool Owned,
668 const PrintingPolicy &Policy);
670 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
671 unsigned &DiagID, Expr *Rep,
672 const PrintingPolicy &policy);
673 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
674 const char *&PrevSpec, unsigned &DiagID,
675 const PrintingPolicy &Policy);
676 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
677 const char *&PrevSpec, unsigned &DiagID,
678 const PrintingPolicy &Policy);
679 bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
680 const char *&PrevSpec, unsigned &DiagID,
681 const PrintingPolicy &Policy);
682 bool SetTypePipe(bool isPipe, SourceLocation Loc,
683 const char *&PrevSpec, unsigned &DiagID,
684 const PrintingPolicy &Policy);
685 bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
687 bool SetTypeSpecError();
688 void UpdateDeclRep(Decl *Rep) {
689 assert(isDeclRep((TST) TypeSpecType));
692 void UpdateTypeRep(ParsedType Rep) {
693 assert(isTypeRep((TST) TypeSpecType));
696 void UpdateExprRep(Expr *Rep) {
697 assert(isExprRep((TST) TypeSpecType));
701 bool SetTypeQual(TQ T, SourceLocation Loc);
703 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
704 unsigned &DiagID, const LangOptions &Lang);
706 bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
708 bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
710 bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
712 bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
713 unsigned &DiagID, ExplicitSpecifier ExplicitSpec,
714 SourceLocation CloseParenLoc);
715 bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
718 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
720 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
722 bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc,
723 const char *&PrevSpec, unsigned &DiagID);
725 bool isFriendSpecified() const { return Friend_specified; }
726 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
728 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
729 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
731 ConstexprSpecKind getConstexprSpecifier() const {
732 return ConstexprSpecKind(ConstexprSpecifier);
735 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
736 bool hasConstexprSpecifier() const {
737 return ConstexprSpecifier != CSK_unspecified;
740 void ClearConstexprSpec() {
741 ConstexprSpecifier = CSK_unspecified;
742 ConstexprLoc = SourceLocation();
745 AttributePool &getAttributePool() const {
746 return Attrs.getPool();
749 /// Concatenates two attribute lists.
751 /// The GCC attribute syntax allows for the following:
754 /// short __attribute__(( unused, deprecated ))
755 /// int __attribute__(( may_alias, aligned(16) )) var;
758 /// This declares 4 attributes using 2 lists. The following syntax is
759 /// also allowed and equivalent to the previous declaration.
762 /// short __attribute__((unused)) __attribute__((deprecated))
763 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
766 void addAttributes(ParsedAttributesView &AL) {
767 Attrs.addAll(AL.begin(), AL.end());
770 bool hasAttributes() const { return !Attrs.empty(); }
772 ParsedAttributes &getAttributes() { return Attrs; }
773 const ParsedAttributes &getAttributes() const { return Attrs; }
775 void takeAttributesFrom(ParsedAttributes &attrs) {
776 Attrs.takeAllFrom(attrs);
779 /// Finish - This does final analysis of the declspec, issuing diagnostics for
780 /// things like "_Imaginary" (lacking an FP type). After calling this method,
781 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
782 void Finish(Sema &S, const PrintingPolicy &Policy);
784 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
788 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
789 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
791 /// Checks if this DeclSpec can stand alone, without a Declarator.
793 /// Only tag declspecs can stand alone.
794 bool isMissingDeclaratorOk();
797 /// Captures information about "declaration specifiers" specific to
801 /// ObjCDeclQualifier - Qualifier used on types in method
802 /// declarations. Not all combinations are sensible. Parameters
803 /// can be one of { in, out, inout } with one of { bycopy, byref }.
804 /// Returns can either be { oneway } or not.
806 /// This should be kept in sync with Decl::ObjCDeclQualifier.
807 enum ObjCDeclQualifier {
815 DQ_CSNullability = 0x40
818 /// PropertyAttributeKind - list of property attributes.
819 /// Keep this list in sync with LLVM's Dwarf.h ApplePropertyAttributes.
820 enum ObjCPropertyAttributeKind {
822 DQ_PR_readonly = 0x01,
825 DQ_PR_readwrite = 0x08,
828 DQ_PR_nonatomic = 0x40,
830 DQ_PR_atomic = 0x100,
832 DQ_PR_strong = 0x400,
833 DQ_PR_unsafe_unretained = 0x800,
834 DQ_PR_nullability = 0x1000,
835 DQ_PR_null_resettable = 0x2000,
840 : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
841 Nullability(0), GetterName(nullptr), SetterName(nullptr) { }
843 ObjCDeclQualifier getObjCDeclQualifier() const {
844 return (ObjCDeclQualifier)objcDeclQualifier;
846 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
847 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
849 void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
850 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
853 ObjCPropertyAttributeKind getPropertyAttributes() const {
854 return ObjCPropertyAttributeKind(PropertyAttributes);
856 void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
858 (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
861 NullabilityKind getNullability() const {
862 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
863 (getPropertyAttributes() & DQ_PR_nullability)) &&
864 "Objective-C declspec doesn't have nullability");
865 return static_cast<NullabilityKind>(Nullability);
868 SourceLocation getNullabilityLoc() const {
869 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
870 (getPropertyAttributes() & DQ_PR_nullability)) &&
871 "Objective-C declspec doesn't have nullability");
872 return NullabilityLoc;
875 void setNullability(SourceLocation loc, NullabilityKind kind) {
876 assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
877 (getPropertyAttributes() & DQ_PR_nullability)) &&
878 "Set the nullability declspec or property attribute first");
879 Nullability = static_cast<unsigned>(kind);
880 NullabilityLoc = loc;
883 const IdentifierInfo *getGetterName() const { return GetterName; }
884 IdentifierInfo *getGetterName() { return GetterName; }
885 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
886 void setGetterName(IdentifierInfo *name, SourceLocation loc) {
891 const IdentifierInfo *getSetterName() const { return SetterName; }
892 IdentifierInfo *getSetterName() { return SetterName; }
893 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
894 void setSetterName(IdentifierInfo *name, SourceLocation loc) {
900 // FIXME: These two are unrelated and mutually exclusive. So perhaps
901 // we can put them in a union to reflect their mutual exclusivity
902 // (space saving is negligible).
903 unsigned objcDeclQualifier : 7;
905 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
906 unsigned PropertyAttributes : 15;
908 unsigned Nullability : 2;
910 SourceLocation NullabilityLoc;
912 IdentifierInfo *GetterName; // getter name or NULL if no getter
913 IdentifierInfo *SetterName; // setter name or NULL if no setter
914 SourceLocation GetterNameLoc; // location of the getter attribute's value
915 SourceLocation SetterNameLoc; // location of the setter attribute's value
919 /// Describes the kind of unqualified-id parsed.
920 enum class UnqualifiedIdKind {
923 /// An overloaded operator name, e.g., operator+.
924 IK_OperatorFunctionId,
925 /// A conversion function name, e.g., operator int.
926 IK_ConversionFunctionId,
927 /// A user-defined literal name, e.g., operator "" _i.
928 IK_LiteralOperatorId,
929 /// A constructor name.
931 /// A constructor named via a template-id.
932 IK_ConstructorTemplateId,
933 /// A destructor name.
935 /// A template-id, e.g., f<int>.
937 /// An implicit 'self' parameter
938 IK_ImplicitSelfParam,
939 /// A deduction-guide name (a template-name)
940 IK_DeductionGuideName
943 /// Represents a C++ unqualified-id that has been parsed.
944 class UnqualifiedId {
946 UnqualifiedId(const UnqualifiedId &Other) = delete;
947 const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
950 /// Describes the kind of unqualified-id parsed.
951 UnqualifiedIdKind Kind;
954 /// The kind of overloaded operator.
955 OverloadedOperatorKind Operator;
957 /// The source locations of the individual tokens that name
958 /// the operator, e.g., the "new", "[", and "]" tokens in
961 /// Different operators have different numbers of tokens in their name,
962 /// up to three. Any remaining source locations in this array will be
963 /// set to an invalid value for operators with fewer than three tokens.
964 unsigned SymbolLocations[3];
967 /// Anonymous union that holds extra data associated with the
968 /// parsed unqualified-id.
970 /// When Kind == IK_Identifier, the parsed identifier, or when
971 /// Kind == IK_UserLiteralId, the identifier suffix.
972 IdentifierInfo *Identifier;
974 /// When Kind == IK_OperatorFunctionId, the overloaded operator
976 struct OFI OperatorFunctionId;
978 /// When Kind == IK_ConversionFunctionId, the type that the
979 /// conversion function names.
980 UnionParsedType ConversionFunctionId;
982 /// When Kind == IK_ConstructorName, the class-name of the type
983 /// whose constructor is being referenced.
984 UnionParsedType ConstructorName;
986 /// When Kind == IK_DestructorName, the type referred to by the
988 UnionParsedType DestructorName;
990 /// When Kind == IK_DeductionGuideName, the parsed template-name.
991 UnionParsedTemplateTy TemplateName;
993 /// When Kind == IK_TemplateId or IK_ConstructorTemplateId,
994 /// the template-id annotation that contains the template name and
995 /// template arguments.
996 TemplateIdAnnotation *TemplateId;
999 /// The location of the first token that describes this unqualified-id,
1000 /// which will be the location of the identifier, "operator" keyword,
1001 /// tilde (for a destructor), or the template name of a template-id.
1002 SourceLocation StartLocation;
1004 /// The location of the last token that describes this unqualified-id.
1005 SourceLocation EndLocation;
1008 : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
1010 /// Clear out this unqualified-id, setting it to default (invalid)
1013 Kind = UnqualifiedIdKind::IK_Identifier;
1014 Identifier = nullptr;
1015 StartLocation = SourceLocation();
1016 EndLocation = SourceLocation();
1019 /// Determine whether this unqualified-id refers to a valid name.
1020 bool isValid() const { return StartLocation.isValid(); }
1022 /// Determine whether this unqualified-id refers to an invalid name.
1023 bool isInvalid() const { return !isValid(); }
1025 /// Determine what kind of name we have.
1026 UnqualifiedIdKind getKind() const { return Kind; }
1027 void setKind(UnqualifiedIdKind kind) { Kind = kind; }
1029 /// Specify that this unqualified-id was parsed as an identifier.
1031 /// \param Id the parsed identifier.
1032 /// \param IdLoc the location of the parsed identifier.
1033 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1034 Kind = UnqualifiedIdKind::IK_Identifier;
1035 Identifier = const_cast<IdentifierInfo *>(Id);
1036 StartLocation = EndLocation = IdLoc;
1039 /// Specify that this unqualified-id was parsed as an
1040 /// operator-function-id.
1042 /// \param OperatorLoc the location of the 'operator' keyword.
1044 /// \param Op the overloaded operator.
1046 /// \param SymbolLocations the locations of the individual operator symbols
1047 /// in the operator.
1048 void setOperatorFunctionId(SourceLocation OperatorLoc,
1049 OverloadedOperatorKind Op,
1050 SourceLocation SymbolLocations[3]);
1052 /// Specify that this unqualified-id was parsed as a
1053 /// conversion-function-id.
1055 /// \param OperatorLoc the location of the 'operator' keyword.
1057 /// \param Ty the type to which this conversion function is converting.
1059 /// \param EndLoc the location of the last token that makes up the type name.
1060 void setConversionFunctionId(SourceLocation OperatorLoc,
1062 SourceLocation EndLoc) {
1063 Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1064 StartLocation = OperatorLoc;
1065 EndLocation = EndLoc;
1066 ConversionFunctionId = Ty;
1069 /// Specific that this unqualified-id was parsed as a
1070 /// literal-operator-id.
1072 /// \param Id the parsed identifier.
1074 /// \param OpLoc the location of the 'operator' keyword.
1076 /// \param IdLoc the location of the identifier.
1077 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1078 SourceLocation IdLoc) {
1079 Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1080 Identifier = const_cast<IdentifierInfo *>(Id);
1081 StartLocation = OpLoc;
1082 EndLocation = IdLoc;
1085 /// Specify that this unqualified-id was parsed as a constructor name.
1087 /// \param ClassType the class type referred to by the constructor name.
1089 /// \param ClassNameLoc the location of the class name.
1091 /// \param EndLoc the location of the last token that makes up the type name.
1092 void setConstructorName(ParsedType ClassType,
1093 SourceLocation ClassNameLoc,
1094 SourceLocation EndLoc) {
1095 Kind = UnqualifiedIdKind::IK_ConstructorName;
1096 StartLocation = ClassNameLoc;
1097 EndLocation = EndLoc;
1098 ConstructorName = ClassType;
1101 /// Specify that this unqualified-id was parsed as a
1102 /// template-id that names a constructor.
1104 /// \param TemplateId the template-id annotation that describes the parsed
1105 /// template-id. This UnqualifiedId instance will take ownership of the
1106 /// \p TemplateId and will free it on destruction.
1107 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1109 /// Specify that this unqualified-id was parsed as a destructor name.
1111 /// \param TildeLoc the location of the '~' that introduces the destructor
1114 /// \param ClassType the name of the class referred to by the destructor name.
1115 void setDestructorName(SourceLocation TildeLoc,
1116 ParsedType ClassType,
1117 SourceLocation EndLoc) {
1118 Kind = UnqualifiedIdKind::IK_DestructorName;
1119 StartLocation = TildeLoc;
1120 EndLocation = EndLoc;
1121 DestructorName = ClassType;
1124 /// Specify that this unqualified-id was parsed as a template-id.
1126 /// \param TemplateId the template-id annotation that describes the parsed
1127 /// template-id. This UnqualifiedId instance will take ownership of the
1128 /// \p TemplateId and will free it on destruction.
1129 void setTemplateId(TemplateIdAnnotation *TemplateId);
1131 /// Specify that this unqualified-id was parsed as a template-name for
1132 /// a deduction-guide.
1134 /// \param Template The parsed template-name.
1135 /// \param TemplateLoc The location of the parsed template-name.
1136 void setDeductionGuideName(ParsedTemplateTy Template,
1137 SourceLocation TemplateLoc) {
1138 Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1139 TemplateName = Template;
1140 StartLocation = EndLocation = TemplateLoc;
1143 /// Return the source range that covers this unqualified-id.
1144 SourceRange getSourceRange() const LLVM_READONLY {
1145 return SourceRange(StartLocation, EndLocation);
1147 SourceLocation getBeginLoc() const LLVM_READONLY { return StartLocation; }
1148 SourceLocation getEndLoc() const LLVM_READONLY { return EndLocation; }
1151 /// A set of tokens that has been cached for later parsing.
1152 typedef SmallVector<Token, 4> CachedTokens;
1154 /// One instance of this struct is used for each type in a
1155 /// declarator that is parsed.
1157 /// This is intended to be a small value object.
1158 struct DeclaratorChunk {
1160 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1163 /// Loc - The place where this type was defined.
1165 /// EndLoc - If valid, the place where this chunck ends.
1166 SourceLocation EndLoc;
1168 SourceRange getSourceRange() const {
1169 if (EndLoc.isInvalid())
1170 return SourceRange(Loc, Loc);
1171 return SourceRange(Loc, EndLoc);
1174 ParsedAttributesView AttrList;
1176 struct PointerTypeInfo {
1177 /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1178 unsigned TypeQuals : 5;
1180 /// The location of the const-qualifier, if any.
1181 unsigned ConstQualLoc;
1183 /// The location of the volatile-qualifier, if any.
1184 unsigned VolatileQualLoc;
1186 /// The location of the restrict-qualifier, if any.
1187 unsigned RestrictQualLoc;
1189 /// The location of the _Atomic-qualifier, if any.
1190 unsigned AtomicQualLoc;
1192 /// The location of the __unaligned-qualifier, if any.
1193 unsigned UnalignedQualLoc;
1199 struct ReferenceTypeInfo {
1200 /// The type qualifier: restrict. [GNU] C++ extension
1201 bool HasRestrict : 1;
1202 /// True if this is an lvalue reference, false if it's an rvalue reference.
1208 struct ArrayTypeInfo {
1209 /// The type qualifiers for the array:
1210 /// const/volatile/restrict/__unaligned/_Atomic.
1211 unsigned TypeQuals : 5;
1213 /// True if this dimension included the 'static' keyword.
1214 unsigned hasStatic : 1;
1216 /// True if this dimension was [*]. In this case, NumElts is null.
1217 unsigned isStar : 1;
1219 /// This is the size of the array, or null if [] or [*] was specified.
1220 /// Since the parser is multi-purpose, and we don't want to impose a root
1221 /// expression class on all clients, NumElts is untyped.
1227 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1228 /// declarator is parsed. There are two interesting styles of parameters
1230 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1231 /// lists will have information about the identifier, but no type information.
1232 /// Parameter type lists will have type info (if the actions module provides
1233 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1235 IdentifierInfo *Ident;
1236 SourceLocation IdentLoc;
1239 /// DefaultArgTokens - When the parameter's default argument
1240 /// cannot be parsed immediately (because it occurs within the
1241 /// declaration of a member function), it will be stored here as a
1242 /// sequence of tokens to be parsed once the class definition is
1243 /// complete. Non-NULL indicates that there is a default argument.
1244 std::unique_ptr<CachedTokens> DefaultArgTokens;
1246 ParamInfo() = default;
1247 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1249 std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1250 : Ident(ident), IdentLoc(iloc), Param(param),
1251 DefaultArgTokens(std::move(DefArgTokens)) {}
1254 struct TypeAndRange {
1259 struct FunctionTypeInfo {
1260 /// hasPrototype - This is true if the function had at least one typed
1261 /// parameter. If the function is () or (a,b,c), then it has no prototype,
1262 /// and is treated as a K&R-style function.
1263 unsigned hasPrototype : 1;
1265 /// isVariadic - If this function has a prototype, and if that
1266 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1267 /// contains the location of the ellipsis.
1268 unsigned isVariadic : 1;
1270 /// Can this declaration be a constructor-style initializer?
1271 unsigned isAmbiguous : 1;
1273 /// Whether the ref-qualifier (if any) is an lvalue reference.
1274 /// Otherwise, it's an rvalue reference.
1275 unsigned RefQualifierIsLValueRef : 1;
1277 /// ExceptionSpecType - An ExceptionSpecificationType value.
1278 unsigned ExceptionSpecType : 4;
1280 /// DeleteParams - If this is true, we need to delete[] Params.
1281 unsigned DeleteParams : 1;
1283 /// HasTrailingReturnType - If this is true, a trailing return type was
1285 unsigned HasTrailingReturnType : 1;
1287 /// The location of the left parenthesis in the source.
1290 /// When isVariadic is true, the location of the ellipsis in the source.
1291 unsigned EllipsisLoc;
1293 /// The location of the right parenthesis in the source.
1296 /// NumParams - This is the number of formal parameters specified by the
1300 /// NumExceptionsOrDecls - This is the number of types in the
1301 /// dynamic-exception-decl, if the function has one. In C, this is the
1302 /// number of declarations in the function prototype.
1303 unsigned NumExceptionsOrDecls;
1305 /// The location of the ref-qualifier, if any.
1307 /// If this is an invalid location, there is no ref-qualifier.
1308 unsigned RefQualifierLoc;
1310 /// The location of the 'mutable' qualifer in a lambda-declarator, if
1312 unsigned MutableLoc;
1314 /// The beginning location of the exception specification, if any.
1315 unsigned ExceptionSpecLocBeg;
1317 /// The end location of the exception specification, if any.
1318 unsigned ExceptionSpecLocEnd;
1320 /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1321 /// describe the parameters specified by this function declarator. null if
1322 /// there are no parameters specified.
1325 /// DeclSpec for the function with the qualifier related info.
1326 DeclSpec *MethodQualifiers;
1328 /// AtttibuteFactory for the MethodQualifiers.
1329 AttributeFactory *QualAttrFactory;
1332 /// Pointer to a new[]'d array of TypeAndRange objects that
1333 /// contain the types in the function's dynamic exception specification
1334 /// and their locations, if there is one.
1335 TypeAndRange *Exceptions;
1337 /// Pointer to the expression in the noexcept-specifier of this
1338 /// function, if it has one.
1341 /// Pointer to the cached tokens for an exception-specification
1342 /// that has not yet been parsed.
1343 CachedTokens *ExceptionSpecTokens;
1345 /// Pointer to a new[]'d array of declarations that need to be available
1346 /// for lookup inside the function body, if one exists. Does not exist in
1348 NamedDecl **DeclsInPrototype;
1351 /// If HasTrailingReturnType is true, this is the trailing return
1353 UnionParsedType TrailingReturnType;
1355 /// Reset the parameter list to having zero parameters.
1357 /// This is used in various places for error recovery.
1359 for (unsigned I = 0; I < NumParams; ++I)
1360 Params[I].DefaultArgTokens.reset();
1363 DeleteParams = false;
1370 delete QualAttrFactory;
1371 delete MethodQualifiers;
1372 switch (getExceptionSpecType()) {
1376 delete[] Exceptions;
1379 delete ExceptionSpecTokens;
1382 if (NumExceptionsOrDecls != 0)
1383 delete[] DeclsInPrototype;
1388 DeclSpec &getOrCreateMethodQualifiers() {
1389 if (!MethodQualifiers) {
1390 QualAttrFactory = new AttributeFactory();
1391 MethodQualifiers = new DeclSpec(*QualAttrFactory);
1393 return *MethodQualifiers;
1396 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1397 /// like "void foo(a,b,c)". In a function definition, this will be followed
1398 /// by the parameter type definitions.
1399 bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1401 SourceLocation getLParenLoc() const {
1402 return SourceLocation::getFromRawEncoding(LParenLoc);
1405 SourceLocation getEllipsisLoc() const {
1406 return SourceLocation::getFromRawEncoding(EllipsisLoc);
1409 SourceLocation getRParenLoc() const {
1410 return SourceLocation::getFromRawEncoding(RParenLoc);
1413 SourceLocation getExceptionSpecLocBeg() const {
1414 return SourceLocation::getFromRawEncoding(ExceptionSpecLocBeg);
1417 SourceLocation getExceptionSpecLocEnd() const {
1418 return SourceLocation::getFromRawEncoding(ExceptionSpecLocEnd);
1421 SourceRange getExceptionSpecRange() const {
1422 return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1425 /// Retrieve the location of the ref-qualifier, if any.
1426 SourceLocation getRefQualifierLoc() const {
1427 return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1430 /// Retrieve the location of the 'const' qualifier.
1431 SourceLocation getConstQualifierLoc() const {
1432 assert(MethodQualifiers);
1433 return MethodQualifiers->getConstSpecLoc();
1436 /// Retrieve the location of the 'volatile' qualifier.
1437 SourceLocation getVolatileQualifierLoc() const {
1438 assert(MethodQualifiers);
1439 return MethodQualifiers->getVolatileSpecLoc();
1442 /// Retrieve the location of the 'restrict' qualifier.
1443 SourceLocation getRestrictQualifierLoc() const {
1444 assert(MethodQualifiers);
1445 return MethodQualifiers->getRestrictSpecLoc();
1448 /// Retrieve the location of the 'mutable' qualifier, if any.
1449 SourceLocation getMutableLoc() const {
1450 return SourceLocation::getFromRawEncoding(MutableLoc);
1453 /// Determine whether this function declaration contains a
1455 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1457 /// Determine whether this lambda-declarator contains a 'mutable'
1459 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1461 /// Determine whether this method has qualifiers.
1462 bool hasMethodTypeQualifiers() const {
1463 return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
1464 MethodQualifiers->getAttributes().size());
1467 /// Get the type of exception specification this function has.
1468 ExceptionSpecificationType getExceptionSpecType() const {
1469 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1472 /// Get the number of dynamic exception specifications.
1473 unsigned getNumExceptions() const {
1474 assert(ExceptionSpecType != EST_None);
1475 return NumExceptionsOrDecls;
1478 /// Get the non-parameter decls defined within this function
1479 /// prototype. Typically these are tag declarations.
1480 ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1481 assert(ExceptionSpecType == EST_None);
1482 return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1485 /// Determine whether this function declarator had a
1486 /// trailing-return-type.
1487 bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1489 /// Get the trailing-return-type for this function declarator.
1490 ParsedType getTrailingReturnType() const { return TrailingReturnType; }
1493 struct BlockPointerTypeInfo {
1494 /// For now, sema will catch these as invalid.
1495 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1496 unsigned TypeQuals : 5;
1502 struct MemberPointerTypeInfo {
1503 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1504 unsigned TypeQuals : 5;
1505 // CXXScopeSpec has a constructor, so it can't be a direct member.
1506 // So we need some pointer-aligned storage and a bit of trickery.
1507 alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1508 CXXScopeSpec &Scope() {
1509 return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1511 const CXXScopeSpec &Scope() const {
1512 return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1515 Scope().~CXXScopeSpec();
1519 struct PipeTypeInfo {
1520 /// The access writes.
1521 unsigned AccessWrites : 3;
1527 PointerTypeInfo Ptr;
1528 ReferenceTypeInfo Ref;
1530 FunctionTypeInfo Fun;
1531 BlockPointerTypeInfo Cls;
1532 MemberPointerTypeInfo Mem;
1533 PipeTypeInfo PipeInfo;
1538 case DeclaratorChunk::Function: return Fun.destroy();
1539 case DeclaratorChunk::Pointer: return Ptr.destroy();
1540 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1541 case DeclaratorChunk::Reference: return Ref.destroy();
1542 case DeclaratorChunk::Array: return Arr.destroy();
1543 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1544 case DeclaratorChunk::Paren: return;
1545 case DeclaratorChunk::Pipe: return PipeInfo.destroy();
1549 /// If there are attributes applied to this declaratorchunk, return
1551 const ParsedAttributesView &getAttrs() const { return AttrList; }
1552 ParsedAttributesView &getAttrs() { return AttrList; }
1554 /// Return a DeclaratorChunk for a pointer.
1555 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1556 SourceLocation ConstQualLoc,
1557 SourceLocation VolatileQualLoc,
1558 SourceLocation RestrictQualLoc,
1559 SourceLocation AtomicQualLoc,
1560 SourceLocation UnalignedQualLoc) {
1564 I.Ptr.TypeQuals = TypeQuals;
1565 I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding();
1566 I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1567 I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1568 I.Ptr.AtomicQualLoc = AtomicQualLoc.getRawEncoding();
1569 I.Ptr.UnalignedQualLoc = UnalignedQualLoc.getRawEncoding();
1573 /// Return a DeclaratorChunk for a reference.
1574 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1579 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1580 I.Ref.LValueRef = lvalue;
1584 /// Return a DeclaratorChunk for an array.
1585 static DeclaratorChunk getArray(unsigned TypeQuals,
1586 bool isStatic, bool isStar, Expr *NumElts,
1587 SourceLocation LBLoc, SourceLocation RBLoc) {
1592 I.Arr.TypeQuals = TypeQuals;
1593 I.Arr.hasStatic = isStatic;
1594 I.Arr.isStar = isStar;
1595 I.Arr.NumElts = NumElts;
1599 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1600 /// "TheDeclarator" is the declarator that this will be added to.
1601 static DeclaratorChunk getFunction(bool HasProto,
1603 SourceLocation LParenLoc,
1604 ParamInfo *Params, unsigned NumParams,
1605 SourceLocation EllipsisLoc,
1606 SourceLocation RParenLoc,
1607 bool RefQualifierIsLvalueRef,
1608 SourceLocation RefQualifierLoc,
1609 SourceLocation MutableLoc,
1610 ExceptionSpecificationType ESpecType,
1611 SourceRange ESpecRange,
1612 ParsedType *Exceptions,
1613 SourceRange *ExceptionRanges,
1614 unsigned NumExceptions,
1616 CachedTokens *ExceptionSpecTokens,
1617 ArrayRef<NamedDecl *> DeclsInPrototype,
1618 SourceLocation LocalRangeBegin,
1619 SourceLocation LocalRangeEnd,
1620 Declarator &TheDeclarator,
1621 TypeResult TrailingReturnType =
1623 DeclSpec *MethodQualifiers = nullptr);
1625 /// Return a DeclaratorChunk for a block.
1626 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1627 SourceLocation Loc) {
1629 I.Kind = BlockPointer;
1631 I.Cls.TypeQuals = TypeQuals;
1635 /// Return a DeclaratorChunk for a block.
1636 static DeclaratorChunk getPipe(unsigned TypeQuals,
1637 SourceLocation Loc) {
1641 I.Cls.TypeQuals = TypeQuals;
1645 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1647 SourceLocation Loc) {
1649 I.Kind = MemberPointer;
1650 I.Loc = SS.getBeginLoc();
1652 I.Mem.TypeQuals = TypeQuals;
1653 new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1657 /// Return a DeclaratorChunk for a paren.
1658 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1659 SourceLocation RParenLoc) {
1663 I.EndLoc = RParenLoc;
1667 bool isParen() const {
1668 return Kind == Paren;
1672 /// A parsed C++17 decomposition declarator of the form
1673 /// '[' identifier-list ']'
1674 class DecompositionDeclarator {
1677 IdentifierInfo *Name;
1678 SourceLocation NameLoc;
1682 /// The locations of the '[' and ']' tokens.
1683 SourceLocation LSquareLoc, RSquareLoc;
1687 unsigned NumBindings : 31;
1688 unsigned DeleteBindings : 1;
1690 friend class Declarator;
1693 DecompositionDeclarator()
1694 : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1695 DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1696 DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1697 ~DecompositionDeclarator() {
1703 LSquareLoc = RSquareLoc = SourceLocation();
1708 DeleteBindings = false;
1711 ArrayRef<Binding> bindings() const {
1712 return llvm::makeArrayRef(Bindings, NumBindings);
1715 bool isSet() const { return LSquareLoc.isValid(); }
1717 SourceLocation getLSquareLoc() const { return LSquareLoc; }
1718 SourceLocation getRSquareLoc() const { return RSquareLoc; }
1719 SourceRange getSourceRange() const {
1720 return SourceRange(LSquareLoc, RSquareLoc);
1724 /// Described the kind of function definition (if any) provided for
1726 enum FunctionDefinitionKind {
1733 enum class DeclaratorContext {
1734 FileContext, // File scope declaration.
1735 PrototypeContext, // Within a function prototype.
1736 ObjCResultContext, // An ObjC method result type.
1737 ObjCParameterContext,// An ObjC method parameter type.
1738 KNRTypeListContext, // K&R type definition list for formals.
1739 TypeNameContext, // Abstract declarator for types.
1740 FunctionalCastContext, // Type in a C++ functional cast expression.
1741 MemberContext, // Struct/Union field.
1742 BlockContext, // Declaration within a block in a function.
1743 ForContext, // Declaration within first part of a for loop.
1744 InitStmtContext, // Declaration within optional init stmt of if/switch.
1745 ConditionContext, // Condition declaration in a C++ if/switch/while/for.
1746 TemplateParamContext,// Within a template parameter list.
1747 CXXNewContext, // C++ new-expression.
1748 CXXCatchContext, // C++ catch exception-declaration
1749 ObjCCatchContext, // Objective-C catch exception-declaration
1750 BlockLiteralContext, // Block literal declarator.
1751 LambdaExprContext, // Lambda-expression declarator.
1752 LambdaExprParameterContext, // Lambda-expression parameter declarator.
1753 ConversionIdContext, // C++ conversion-type-id.
1754 TrailingReturnContext, // C++11 trailing-type-specifier.
1755 TrailingReturnVarContext, // C++11 trailing-type-specifier for variable.
1756 TemplateArgContext, // Any template argument (in template argument list).
1757 TemplateTypeArgContext, // Template type argument (in default argument).
1758 AliasDeclContext, // C++11 alias-declaration.
1759 AliasTemplateContext // C++11 alias-declaration template.
1763 /// Information about one declarator, including the parsed type
1764 /// information and the identifier.
1766 /// When the declarator is fully formed, this is turned into the appropriate
1769 /// Declarators come in two types: normal declarators and abstract declarators.
1770 /// Abstract declarators are used when parsing types, and don't have an
1771 /// identifier. Normal declarators do have ID's.
1773 /// Instances of this class should be a transient object that lives on the
1774 /// stack, not objects that are allocated in large quantities on the heap.
1783 /// Where we are parsing this declarator.
1784 DeclaratorContext Context;
1786 /// The C++17 structured binding, if any. This is an alternative to a Name.
1787 DecompositionDeclarator BindingGroup;
1789 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1790 /// parsed. This is pushed from the identifier out, which means that element
1791 /// #0 will be the most closely bound to the identifier, and
1792 /// DeclTypeInfo.back() will be the least closely bound.
1793 SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1795 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1796 unsigned InvalidType : 1;
1798 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1799 unsigned GroupingParens : 1;
1801 /// FunctionDefinition - Is this Declarator for a function or member
1802 /// definition and, if so, what kind?
1804 /// Actually a FunctionDefinitionKind.
1805 unsigned FunctionDefinition : 2;
1807 /// Is this Declarator a redeclaration?
1808 unsigned Redeclaration : 1;
1810 /// true if the declaration is preceded by \c __extension__.
1811 unsigned Extension : 1;
1813 /// Indicates whether this is an Objective-C instance variable.
1814 unsigned ObjCIvar : 1;
1816 /// Indicates whether this is an Objective-C 'weak' property.
1817 unsigned ObjCWeakProperty : 1;
1819 /// Indicates whether the InlineParams / InlineBindings storage has been used.
1820 unsigned InlineStorageUsed : 1;
1822 /// Attrs - Attributes.
1823 ParsedAttributes Attrs;
1825 /// The asm label, if specified.
1831 /// InlineParams - This is a local array used for the first function decl
1832 /// chunk to avoid going to the heap for the common case when we have one
1833 /// function chunk in the declarator.
1834 DeclaratorChunk::ParamInfo InlineParams[16];
1835 DecompositionDeclarator::Binding InlineBindings[16];
1840 /// If this is the second or subsequent declarator in this declaration,
1841 /// the location of the comma before this declarator.
1842 SourceLocation CommaLoc;
1844 /// If provided, the source location of the ellipsis used to describe
1845 /// this declarator as a parameter pack.
1846 SourceLocation EllipsisLoc;
1848 friend struct DeclaratorChunk;
1851 Declarator(const DeclSpec &ds, DeclaratorContext C)
1852 : DS(ds), Range(ds.getSourceRange()), Context(C),
1853 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1854 GroupingParens(false), FunctionDefinition(FDK_Declaration),
1855 Redeclaration(false), Extension(false), ObjCIvar(false),
1856 ObjCWeakProperty(false), InlineStorageUsed(false),
1857 Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr) {}
1862 /// getDeclSpec - Return the declaration-specifier that this declarator was
1864 const DeclSpec &getDeclSpec() const { return DS; }
1866 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1867 /// should be used with extreme care: declspecs can often be shared between
1868 /// multiple declarators, so mutating the DeclSpec affects all of the
1869 /// Declarators. This should only be done when the declspec is known to not
1870 /// be shared or when in error recovery etc.
1871 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1873 AttributePool &getAttributePool() const {
1874 return Attrs.getPool();
1877 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1878 /// nested-name-specifier) that is part of the declarator-id.
1879 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1880 CXXScopeSpec &getCXXScopeSpec() { return SS; }
1882 /// Retrieve the name specified by this declarator.
1883 UnqualifiedId &getName() { return Name; }
1885 const DecompositionDeclarator &getDecompositionDeclarator() const {
1886 return BindingGroup;
1889 DeclaratorContext getContext() const { return Context; }
1891 bool isPrototypeContext() const {
1892 return (Context == DeclaratorContext::PrototypeContext ||
1893 Context == DeclaratorContext::ObjCParameterContext ||
1894 Context == DeclaratorContext::ObjCResultContext ||
1895 Context == DeclaratorContext::LambdaExprParameterContext);
1898 /// Get the source range that spans this declarator.
1899 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1900 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
1901 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
1903 void SetSourceRange(SourceRange R) { Range = R; }
1904 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1906 void SetRangeBegin(SourceLocation Loc) {
1907 if (!Loc.isInvalid())
1908 Range.setBegin(Loc);
1910 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1911 void SetRangeEnd(SourceLocation Loc) {
1912 if (!Loc.isInvalid())
1915 /// ExtendWithDeclSpec - Extend the declarator source range to include the
1916 /// given declspec, unless its location is invalid. Adopts the range start if
1917 /// the current range start is invalid.
1918 void ExtendWithDeclSpec(const DeclSpec &DS) {
1919 SourceRange SR = DS.getSourceRange();
1920 if (Range.getBegin().isInvalid())
1921 Range.setBegin(SR.getBegin());
1922 if (!SR.getEnd().isInvalid())
1923 Range.setEnd(SR.getEnd());
1926 /// Reset the contents of this Declarator.
1930 Range = DS.getSourceRange();
1931 BindingGroup.clear();
1933 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1934 DeclTypeInfo[i].destroy();
1935 DeclTypeInfo.clear();
1938 InlineStorageUsed = false;
1940 ObjCWeakProperty = false;
1941 CommaLoc = SourceLocation();
1942 EllipsisLoc = SourceLocation();
1945 /// mayOmitIdentifier - Return true if the identifier is either optional or
1946 /// not allowed. This is true for typenames, prototypes, and template
1947 /// parameter lists.
1948 bool mayOmitIdentifier() const {
1950 case DeclaratorContext::FileContext:
1951 case DeclaratorContext::KNRTypeListContext:
1952 case DeclaratorContext::MemberContext:
1953 case DeclaratorContext::BlockContext:
1954 case DeclaratorContext::ForContext:
1955 case DeclaratorContext::InitStmtContext:
1956 case DeclaratorContext::ConditionContext:
1959 case DeclaratorContext::TypeNameContext:
1960 case DeclaratorContext::FunctionalCastContext:
1961 case DeclaratorContext::AliasDeclContext:
1962 case DeclaratorContext::AliasTemplateContext:
1963 case DeclaratorContext::PrototypeContext:
1964 case DeclaratorContext::LambdaExprParameterContext:
1965 case DeclaratorContext::ObjCParameterContext:
1966 case DeclaratorContext::ObjCResultContext:
1967 case DeclaratorContext::TemplateParamContext:
1968 case DeclaratorContext::CXXNewContext:
1969 case DeclaratorContext::CXXCatchContext:
1970 case DeclaratorContext::ObjCCatchContext:
1971 case DeclaratorContext::BlockLiteralContext:
1972 case DeclaratorContext::LambdaExprContext:
1973 case DeclaratorContext::ConversionIdContext:
1974 case DeclaratorContext::TemplateArgContext:
1975 case DeclaratorContext::TemplateTypeArgContext:
1976 case DeclaratorContext::TrailingReturnContext:
1977 case DeclaratorContext::TrailingReturnVarContext:
1980 llvm_unreachable("unknown context kind!");
1983 /// mayHaveIdentifier - Return true if the identifier is either optional or
1984 /// required. This is true for normal declarators and prototypes, but not
1986 bool mayHaveIdentifier() const {
1988 case DeclaratorContext::FileContext:
1989 case DeclaratorContext::KNRTypeListContext:
1990 case DeclaratorContext::MemberContext:
1991 case DeclaratorContext::BlockContext:
1992 case DeclaratorContext::ForContext:
1993 case DeclaratorContext::InitStmtContext:
1994 case DeclaratorContext::ConditionContext:
1995 case DeclaratorContext::PrototypeContext:
1996 case DeclaratorContext::LambdaExprParameterContext:
1997 case DeclaratorContext::TemplateParamContext:
1998 case DeclaratorContext::CXXCatchContext:
1999 case DeclaratorContext::ObjCCatchContext:
2002 case DeclaratorContext::TypeNameContext:
2003 case DeclaratorContext::FunctionalCastContext:
2004 case DeclaratorContext::CXXNewContext:
2005 case DeclaratorContext::AliasDeclContext:
2006 case DeclaratorContext::AliasTemplateContext:
2007 case DeclaratorContext::ObjCParameterContext:
2008 case DeclaratorContext::ObjCResultContext:
2009 case DeclaratorContext::BlockLiteralContext:
2010 case DeclaratorContext::LambdaExprContext:
2011 case DeclaratorContext::ConversionIdContext:
2012 case DeclaratorContext::TemplateArgContext:
2013 case DeclaratorContext::TemplateTypeArgContext:
2014 case DeclaratorContext::TrailingReturnContext:
2015 case DeclaratorContext::TrailingReturnVarContext:
2018 llvm_unreachable("unknown context kind!");
2021 /// Return true if the context permits a C++17 decomposition declarator.
2022 bool mayHaveDecompositionDeclarator() const {
2024 case DeclaratorContext::FileContext:
2025 // FIXME: It's not clear that the proposal meant to allow file-scope
2026 // structured bindings, but it does.
2027 case DeclaratorContext::BlockContext:
2028 case DeclaratorContext::ForContext:
2029 case DeclaratorContext::InitStmtContext:
2030 case DeclaratorContext::ConditionContext:
2033 case DeclaratorContext::MemberContext:
2034 case DeclaratorContext::PrototypeContext:
2035 case DeclaratorContext::TemplateParamContext:
2039 // These contexts don't allow any kind of non-abstract declarator.
2040 case DeclaratorContext::KNRTypeListContext:
2041 case DeclaratorContext::TypeNameContext:
2042 case DeclaratorContext::FunctionalCastContext:
2043 case DeclaratorContext::AliasDeclContext:
2044 case DeclaratorContext::AliasTemplateContext:
2045 case DeclaratorContext::LambdaExprParameterContext:
2046 case DeclaratorContext::ObjCParameterContext:
2047 case DeclaratorContext::ObjCResultContext:
2048 case DeclaratorContext::CXXNewContext:
2049 case DeclaratorContext::CXXCatchContext:
2050 case DeclaratorContext::ObjCCatchContext:
2051 case DeclaratorContext::BlockLiteralContext:
2052 case DeclaratorContext::LambdaExprContext:
2053 case DeclaratorContext::ConversionIdContext:
2054 case DeclaratorContext::TemplateArgContext:
2055 case DeclaratorContext::TemplateTypeArgContext:
2056 case DeclaratorContext::TrailingReturnContext:
2057 case DeclaratorContext::TrailingReturnVarContext:
2060 llvm_unreachable("unknown context kind!");
2063 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2064 /// followed by a C++ direct initializer, e.g. "int x(1);".
2065 bool mayBeFollowedByCXXDirectInit() const {
2066 if (hasGroupingParens()) return false;
2068 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2071 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2072 Context != DeclaratorContext::FileContext)
2075 // Special names can't have direct initializers.
2076 if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2080 case DeclaratorContext::FileContext:
2081 case DeclaratorContext::BlockContext:
2082 case DeclaratorContext::ForContext:
2083 case DeclaratorContext::InitStmtContext:
2084 case DeclaratorContext::TrailingReturnVarContext:
2087 case DeclaratorContext::ConditionContext:
2088 // This may not be followed by a direct initializer, but it can't be a
2089 // function declaration either, and we'd prefer to perform a tentative
2090 // parse in order to produce the right diagnostic.
2093 case DeclaratorContext::KNRTypeListContext:
2094 case DeclaratorContext::MemberContext:
2095 case DeclaratorContext::PrototypeContext:
2096 case DeclaratorContext::LambdaExprParameterContext:
2097 case DeclaratorContext::ObjCParameterContext:
2098 case DeclaratorContext::ObjCResultContext:
2099 case DeclaratorContext::TemplateParamContext:
2100 case DeclaratorContext::CXXCatchContext:
2101 case DeclaratorContext::ObjCCatchContext:
2102 case DeclaratorContext::TypeNameContext:
2103 case DeclaratorContext::FunctionalCastContext: // FIXME
2104 case DeclaratorContext::CXXNewContext:
2105 case DeclaratorContext::AliasDeclContext:
2106 case DeclaratorContext::AliasTemplateContext:
2107 case DeclaratorContext::BlockLiteralContext:
2108 case DeclaratorContext::LambdaExprContext:
2109 case DeclaratorContext::ConversionIdContext:
2110 case DeclaratorContext::TemplateArgContext:
2111 case DeclaratorContext::TemplateTypeArgContext:
2112 case DeclaratorContext::TrailingReturnContext:
2115 llvm_unreachable("unknown context kind!");
2118 /// isPastIdentifier - Return true if we have parsed beyond the point where
2119 /// the name would appear. (This may happen even if we haven't actually parsed
2120 /// a name, perhaps because this context doesn't require one.)
2121 bool isPastIdentifier() const { return Name.isValid(); }
2123 /// hasName - Whether this declarator has a name, which might be an
2124 /// identifier (accessible via getIdentifier()) or some kind of
2125 /// special C++ name (constructor, destructor, etc.), or a structured
2126 /// binding (which is not exactly a name, but occupies the same position).
2127 bool hasName() const {
2128 return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2129 Name.Identifier || isDecompositionDeclarator();
2132 /// Return whether this declarator is a decomposition declarator.
2133 bool isDecompositionDeclarator() const {
2134 return BindingGroup.isSet();
2137 IdentifierInfo *getIdentifier() const {
2138 if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2139 return Name.Identifier;
2143 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2145 /// Set the name of this declarator to be the given identifier.
2146 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2147 Name.setIdentifier(Id, IdLoc);
2150 /// Set the decomposition bindings for this declarator.
2152 setDecompositionBindings(SourceLocation LSquareLoc,
2153 ArrayRef<DecompositionDeclarator::Binding> Bindings,
2154 SourceLocation RSquareLoc);
2156 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2157 /// EndLoc, which should be the last token of the chunk.
2158 /// This function takes attrs by R-Value reference because it takes ownership
2159 /// of those attributes from the parameter.
2160 void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
2161 SourceLocation EndLoc) {
2162 DeclTypeInfo.push_back(TI);
2163 DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end());
2164 getAttributePool().takeAllFrom(attrs.getPool());
2166 if (!EndLoc.isInvalid())
2167 SetRangeEnd(EndLoc);
2170 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2171 /// EndLoc, which should be the last token of the chunk.
2172 void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
2173 DeclTypeInfo.push_back(TI);
2175 if (!EndLoc.isInvalid())
2176 SetRangeEnd(EndLoc);
2179 /// Add a new innermost chunk to this declarator.
2180 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2181 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2184 /// Return the number of types applied to this declarator.
2185 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2187 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
2188 /// closest to the identifier.
2189 const DeclaratorChunk &getTypeObject(unsigned i) const {
2190 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2191 return DeclTypeInfo[i];
2193 DeclaratorChunk &getTypeObject(unsigned i) {
2194 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2195 return DeclTypeInfo[i];
2198 typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2199 typedef llvm::iterator_range<type_object_iterator> type_object_range;
2201 /// Returns the range of type objects, from the identifier outwards.
2202 type_object_range type_objects() const {
2203 return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2206 void DropFirstTypeObject() {
2207 assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
2208 DeclTypeInfo.front().destroy();
2209 DeclTypeInfo.erase(DeclTypeInfo.begin());
2212 /// Return the innermost (closest to the declarator) chunk of this
2213 /// declarator that is not a parens chunk, or null if there are no
2214 /// non-parens chunks.
2215 const DeclaratorChunk *getInnermostNonParenChunk() const {
2216 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2217 if (!DeclTypeInfo[i].isParen())
2218 return &DeclTypeInfo[i];
2223 /// Return the outermost (furthest from the declarator) chunk of
2224 /// this declarator that is not a parens chunk, or null if there are
2225 /// no non-parens chunks.
2226 const DeclaratorChunk *getOutermostNonParenChunk() const {
2227 for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2228 if (!DeclTypeInfo[i-1].isParen())
2229 return &DeclTypeInfo[i-1];
2234 /// isArrayOfUnknownBound - This method returns true if the declarator
2235 /// is a declarator for an array of unknown bound (looking through
2237 bool isArrayOfUnknownBound() const {
2238 const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2239 return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2240 !chunk->Arr.NumElts);
2243 /// isFunctionDeclarator - This method returns true if the declarator
2244 /// is a function declarator (looking through parentheses).
2245 /// If true is returned, then the reference type parameter idx is
2246 /// assigned with the index of the declaration chunk.
2247 bool isFunctionDeclarator(unsigned& idx) const {
2248 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2249 switch (DeclTypeInfo[i].Kind) {
2250 case DeclaratorChunk::Function:
2253 case DeclaratorChunk::Paren:
2255 case DeclaratorChunk::Pointer:
2256 case DeclaratorChunk::Reference:
2257 case DeclaratorChunk::Array:
2258 case DeclaratorChunk::BlockPointer:
2259 case DeclaratorChunk::MemberPointer:
2260 case DeclaratorChunk::Pipe:
2263 llvm_unreachable("Invalid type chunk");
2268 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2269 /// this method returns true if the identifier is a function declarator
2270 /// (looking through parentheses).
2271 bool isFunctionDeclarator() const {
2273 return isFunctionDeclarator(index);
2276 /// getFunctionTypeInfo - Retrieves the function type info object
2277 /// (looking through parentheses).
2278 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2279 assert(isFunctionDeclarator() && "Not a function declarator!");
2281 isFunctionDeclarator(index);
2282 return DeclTypeInfo[index].Fun;
2285 /// getFunctionTypeInfo - Retrieves the function type info object
2286 /// (looking through parentheses).
2287 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2288 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2291 /// Determine whether the declaration that will be produced from
2292 /// this declaration will be a function.
2294 /// A declaration can declare a function even if the declarator itself
2295 /// isn't a function declarator, if the type specifier refers to a function
2296 /// type. This routine checks for both cases.
2297 bool isDeclarationOfFunction() const;
2299 /// Return true if this declaration appears in a context where a
2300 /// function declarator would be a function declaration.
2301 bool isFunctionDeclarationContext() const {
2302 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2306 case DeclaratorContext::FileContext:
2307 case DeclaratorContext::MemberContext:
2308 case DeclaratorContext::BlockContext:
2309 case DeclaratorContext::ForContext:
2310 case DeclaratorContext::InitStmtContext:
2313 case DeclaratorContext::ConditionContext:
2314 case DeclaratorContext::KNRTypeListContext:
2315 case DeclaratorContext::TypeNameContext:
2316 case DeclaratorContext::FunctionalCastContext:
2317 case DeclaratorContext::AliasDeclContext:
2318 case DeclaratorContext::AliasTemplateContext:
2319 case DeclaratorContext::PrototypeContext:
2320 case DeclaratorContext::LambdaExprParameterContext:
2321 case DeclaratorContext::ObjCParameterContext:
2322 case DeclaratorContext::ObjCResultContext:
2323 case DeclaratorContext::TemplateParamContext:
2324 case DeclaratorContext::CXXNewContext:
2325 case DeclaratorContext::CXXCatchContext:
2326 case DeclaratorContext::ObjCCatchContext:
2327 case DeclaratorContext::BlockLiteralContext:
2328 case DeclaratorContext::LambdaExprContext:
2329 case DeclaratorContext::ConversionIdContext:
2330 case DeclaratorContext::TemplateArgContext:
2331 case DeclaratorContext::TemplateTypeArgContext:
2332 case DeclaratorContext::TrailingReturnContext:
2333 case DeclaratorContext::TrailingReturnVarContext:
2336 llvm_unreachable("unknown context kind!");
2339 /// Determine whether this declaration appears in a context where an
2340 /// expression could appear.
2341 bool isExpressionContext() const {
2343 case DeclaratorContext::FileContext:
2344 case DeclaratorContext::KNRTypeListContext:
2345 case DeclaratorContext::MemberContext:
2347 // FIXME: sizeof(...) permits an expression.
2348 case DeclaratorContext::TypeNameContext:
2350 case DeclaratorContext::FunctionalCastContext:
2351 case DeclaratorContext::AliasDeclContext:
2352 case DeclaratorContext::AliasTemplateContext:
2353 case DeclaratorContext::PrototypeContext:
2354 case DeclaratorContext::LambdaExprParameterContext:
2355 case DeclaratorContext::ObjCParameterContext:
2356 case DeclaratorContext::ObjCResultContext:
2357 case DeclaratorContext::TemplateParamContext:
2358 case DeclaratorContext::CXXNewContext:
2359 case DeclaratorContext::CXXCatchContext:
2360 case DeclaratorContext::ObjCCatchContext:
2361 case DeclaratorContext::BlockLiteralContext:
2362 case DeclaratorContext::LambdaExprContext:
2363 case DeclaratorContext::ConversionIdContext:
2364 case DeclaratorContext::TrailingReturnContext:
2365 case DeclaratorContext::TrailingReturnVarContext:
2366 case DeclaratorContext::TemplateTypeArgContext:
2369 case DeclaratorContext::BlockContext:
2370 case DeclaratorContext::ForContext:
2371 case DeclaratorContext::InitStmtContext:
2372 case DeclaratorContext::ConditionContext:
2373 case DeclaratorContext::TemplateArgContext:
2377 llvm_unreachable("unknown context kind!");
2380 /// Return true if a function declarator at this position would be a
2381 /// function declaration.
2382 bool isFunctionDeclaratorAFunctionDeclaration() const {
2383 if (!isFunctionDeclarationContext())
2386 for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2387 if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2393 /// Determine whether a trailing return type was written (at any
2394 /// level) within this declarator.
2395 bool hasTrailingReturnType() const {
2396 for (const auto &Chunk : type_objects())
2397 if (Chunk.Kind == DeclaratorChunk::Function &&
2398 Chunk.Fun.hasTrailingReturnType())
2403 /// takeAttributes - Takes attributes from the given parsed-attributes
2404 /// set and add them to this declarator.
2406 /// These examples both add 3 attributes to "var":
2407 /// short int var __attribute__((aligned(16),common,deprecated));
2408 /// short int x, __attribute__((aligned(16)) var
2409 /// __attribute__((common,deprecated));
2411 /// Also extends the range of the declarator.
2412 void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2413 Attrs.takeAllFrom(attrs);
2415 if (!lastLoc.isInvalid())
2416 SetRangeEnd(lastLoc);
2419 const ParsedAttributes &getAttributes() const { return Attrs; }
2420 ParsedAttributes &getAttributes() { return Attrs; }
2422 /// hasAttributes - do we contain any attributes?
2423 bool hasAttributes() const {
2424 if (!getAttributes().empty() || getDeclSpec().hasAttributes())
2426 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2427 if (!getTypeObject(i).getAttrs().empty())
2432 /// Return a source range list of C++11 attributes associated
2433 /// with the declarator.
2434 void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2435 for (const ParsedAttr &AL : Attrs)
2436 if (AL.isCXX11Attribute())
2437 Ranges.push_back(AL.getRange());
2440 void setAsmLabel(Expr *E) { AsmLabel = E; }
2441 Expr *getAsmLabel() const { return AsmLabel; }
2443 void setExtension(bool Val = true) { Extension = Val; }
2444 bool getExtension() const { return Extension; }
2446 void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2447 bool isObjCIvar() const { return ObjCIvar; }
2449 void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2450 bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2452 void setInvalidType(bool Val = true) { InvalidType = Val; }
2453 bool isInvalidType() const {
2454 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2457 void setGroupingParens(bool flag) { GroupingParens = flag; }
2458 bool hasGroupingParens() const { return GroupingParens; }
2460 bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2461 SourceLocation getCommaLoc() const { return CommaLoc; }
2462 void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2464 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2465 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2466 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2468 void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2469 FunctionDefinition = Val;
2472 bool isFunctionDefinition() const {
2473 return getFunctionDefinitionKind() != FDK_Declaration;
2476 FunctionDefinitionKind getFunctionDefinitionKind() const {
2477 return (FunctionDefinitionKind)FunctionDefinition;
2480 /// Returns true if this declares a real member and not a friend.
2481 bool isFirstDeclarationOfMember() {
2482 return getContext() == DeclaratorContext::MemberContext &&
2483 !getDeclSpec().isFriendSpecified();
2486 /// Returns true if this declares a static member. This cannot be called on a
2487 /// declarator outside of a MemberContext because we won't know until
2488 /// redeclaration time if the decl is static.
2489 bool isStaticMember();
2491 /// Returns true if this declares a constructor or a destructor.
2492 bool isCtorOrDtor();
2494 void setRedeclaration(bool Val) { Redeclaration = Val; }
2495 bool isRedeclaration() const { return Redeclaration; }
2498 /// This little struct is used to capture information about
2499 /// structure field declarators, which is basically just a bitfield size.
2500 struct FieldDeclarator {
2503 explicit FieldDeclarator(const DeclSpec &DS)
2504 : D(DS, DeclaratorContext::MemberContext),
2505 BitfieldSize(nullptr) {}
2508 /// Represents a C++11 virt-specifier-seq.
2509 class VirtSpecifiers {
2516 // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2520 VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2522 bool SetSpecifier(Specifier VS, SourceLocation Loc,
2523 const char *&PrevSpec);
2525 bool isUnset() const { return Specifiers == 0; }
2527 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2528 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2530 bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2531 bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2532 SourceLocation getFinalLoc() const { return VS_finalLoc; }
2534 void clear() { Specifiers = 0; }
2536 static const char *getSpecifierName(Specifier VS);
2538 SourceLocation getFirstLocation() const { return FirstLocation; }
2539 SourceLocation getLastLocation() const { return LastLocation; }
2540 Specifier getLastSpecifier() const { return LastSpecifier; }
2543 unsigned Specifiers;
2544 Specifier LastSpecifier;
2546 SourceLocation VS_overrideLoc, VS_finalLoc;
2547 SourceLocation FirstLocation;
2548 SourceLocation LastLocation;
2551 enum class LambdaCaptureInitKind {
2553 CopyInit, //!< [a = b], [a = {b}]
2554 DirectInit, //!< [a(b)]
2555 ListInit //!< [a{b}]
2558 /// Represents a complete lambda introducer.
2559 struct LambdaIntroducer {
2560 /// An individual capture in a lambda introducer.
2561 struct LambdaCapture {
2562 LambdaCaptureKind Kind;
2565 SourceLocation EllipsisLoc;
2566 LambdaCaptureInitKind InitKind;
2568 ParsedType InitCaptureType;
2569 SourceRange ExplicitRange;
2571 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2572 IdentifierInfo *Id, SourceLocation EllipsisLoc,
2573 LambdaCaptureInitKind InitKind, ExprResult Init,
2574 ParsedType InitCaptureType,
2575 SourceRange ExplicitRange)
2576 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2577 InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
2578 ExplicitRange(ExplicitRange) {}
2582 SourceLocation DefaultLoc;
2583 LambdaCaptureDefault Default;
2584 SmallVector<LambdaCapture, 4> Captures;
2587 : Default(LCD_None) {}
2589 /// Append a capture in a lambda introducer.
2590 void addCapture(LambdaCaptureKind Kind,
2593 SourceLocation EllipsisLoc,
2594 LambdaCaptureInitKind InitKind,
2596 ParsedType InitCaptureType,
2597 SourceRange ExplicitRange) {
2598 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2599 InitCaptureType, ExplicitRange));
2603 } // end namespace clang
2605 #endif // LLVM_CLANG_SEMA_DECLSPEC_H