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 //===----------------------------------------------------------------------===//
10 // This file defines the classes used to store parsed information about
11 // declaration-specifiers and declarators.
13 // static const int volatile x, *y, *(*(*z)[10])(const void *x);
14 // ------------------------- - -- ---------------------------
15 // declaration-specifiers \ | /
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_CLANG_SEMA_DECLSPEC_H
21 #define LLVM_CLANG_SEMA_DECLSPEC_H
23 #include "clang/Sema/AttributeList.h"
24 #include "clang/Sema/Ownership.h"
25 #include "clang/AST/NestedNameSpecifier.h"
26 #include "clang/Lex/Token.h"
27 #include "clang/Basic/ExceptionSpecificationType.h"
28 #include "clang/Basic/OperatorKinds.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/ErrorHandling.h"
37 class DiagnosticsEngine;
39 class NamespaceAliasDecl;
41 class NestedNameSpecifier;
42 class NestedNameSpecifierLoc;
47 struct TemplateIdAnnotation;
49 /// CXXScopeSpec - Represents a C++ nested-name-specifier or a global scope
50 /// specifier. These can be in 3 states:
51 /// 1) Not present, identified by isEmpty()
52 /// 2) Present, identified by isNotEmpty()
53 /// 2.a) Valid, idenified by isValid()
54 /// 2.b) Invalid, identified by isInvalid().
56 /// isSet() is deprecated because it mostly corresponded to "valid" but was
57 /// often used as if it meant "present".
59 /// The actual scope is described by getScopeRep().
62 NestedNameSpecifierLocBuilder Builder;
65 const SourceRange &getRange() const { return Range; }
66 void setRange(const SourceRange &R) { Range = R; }
67 void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
68 void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
69 SourceLocation getBeginLoc() const { return Range.getBegin(); }
70 SourceLocation getEndLoc() const { return Range.getEnd(); }
72 /// \brief Retrieve the representation of the nested-name-specifier.
73 NestedNameSpecifier *getScopeRep() const {
74 return Builder.getRepresentation();
77 /// \brief Extend the current nested-name-specifier by another
78 /// nested-name-specifier component of the form 'type::'.
80 /// \param Context The AST context in which this nested-name-specifier
83 /// \param TemplateKWLoc The location of the 'template' keyword, if present.
85 /// \param TL The TypeLoc that describes the type preceding the '::'.
87 /// \param ColonColonLoc The location of the trailing '::'.
88 void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
89 SourceLocation ColonColonLoc);
91 /// \brief Extend the current nested-name-specifier by another
92 /// nested-name-specifier component of the form 'identifier::'.
94 /// \param Context The AST context in which this nested-name-specifier
97 /// \param Identifier The identifier.
99 /// \param IdentifierLoc The location of the identifier.
101 /// \param ColonColonLoc The location of the trailing '::'.
102 void Extend(ASTContext &Context, IdentifierInfo *Identifier,
103 SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
105 /// \brief Extend the current nested-name-specifier by another
106 /// nested-name-specifier component of the form 'namespace::'.
108 /// \param Context The AST context in which this nested-name-specifier
111 /// \param Namespace The namespace.
113 /// \param NamespaceLoc The location of the namespace name.
115 /// \param ColonColonLoc The location of the trailing '::'.
116 void Extend(ASTContext &Context, NamespaceDecl *Namespace,
117 SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
119 /// \brief Extend the current nested-name-specifier by another
120 /// nested-name-specifier component of the form 'namespace-alias::'.
122 /// \param Context The AST context in which this nested-name-specifier
125 /// \param Alias The namespace alias.
127 /// \param AliasLoc The location of the namespace alias
130 /// \param ColonColonLoc The location of the trailing '::'.
131 void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
132 SourceLocation AliasLoc, SourceLocation ColonColonLoc);
134 /// \brief Turn this (empty) nested-name-specifier into the global
135 /// nested-name-specifier '::'.
136 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
138 /// \brief Make a new nested-name-specifier from incomplete source-location
141 /// FIXME: This routine should be used very, very rarely, in cases where we
142 /// need to synthesize a nested-name-specifier. Most code should instead use
143 /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
144 void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
147 /// \brief Adopt an existing nested-name-specifier (with source-range
149 void Adopt(NestedNameSpecifierLoc Other);
151 /// \brief Retrieve a nested-name-specifier with location information, copied
152 /// into the given AST context.
154 /// \param Context The context into which this nested-name-specifier will be
156 NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
158 /// \brief Retrieve the location of the name in the last qualifier
159 /// in this nested name specifier. For example:
162 SourceLocation getLastQualifierNameLoc() const;
164 /// No scope specifier.
165 bool isEmpty() const { return !Range.isValid(); }
166 /// A scope specifier is present, but may be valid or invalid.
167 bool isNotEmpty() const { return !isEmpty(); }
169 /// An error occurred during parsing of the scope specifier.
170 bool isInvalid() const { return isNotEmpty() && getScopeRep() == 0; }
171 /// A scope specifier is present, and it refers to a real scope.
172 bool isValid() const { return isNotEmpty() && getScopeRep() != 0; }
174 /// \brief Indicate that this nested-name-specifier is invalid.
175 void SetInvalid(SourceRange R) {
176 assert(R.isValid() && "Must have a valid source range");
177 if (Range.getBegin().isInvalid())
178 Range.setBegin(R.getBegin());
179 Range.setEnd(R.getEnd());
183 /// Deprecated. Some call sites intend isNotEmpty() while others intend
185 bool isSet() const { return getScopeRep() != 0; }
188 Range = SourceRange();
192 /// \brief Retrieve the data associated with the source-location information.
193 char *location_data() const { return Builder.getBuffer().first; }
195 /// \brief Retrieve the size of the data associated with source-location
197 unsigned location_size() const { return Builder.getBuffer().second; }
200 /// DeclSpec - This class captures information about "declaration specifiers",
201 /// which encompasses storage-class-specifiers, type-specifiers,
202 /// type-qualifiers, and function-specifiers.
205 // storage-class-specifier
206 // Note: The order of these enumerators is important for diagnostics.
218 // Import type specifier width enumeration and constants.
219 typedef TypeSpecifierWidth TSW;
220 static const TSW TSW_unspecified = clang::TSW_unspecified;
221 static const TSW TSW_short = clang::TSW_short;
222 static const TSW TSW_long = clang::TSW_long;
223 static const TSW TSW_longlong = clang::TSW_longlong;
231 // Import type specifier sign enumeration and constants.
232 typedef TypeSpecifierSign TSS;
233 static const TSS TSS_unspecified = clang::TSS_unspecified;
234 static const TSS TSS_signed = clang::TSS_signed;
235 static const TSS TSS_unsigned = clang::TSS_unsigned;
237 // Import type specifier type enumeration and constants.
238 typedef TypeSpecifierType TST;
239 static const TST TST_unspecified = clang::TST_unspecified;
240 static const TST TST_void = clang::TST_void;
241 static const TST TST_char = clang::TST_char;
242 static const TST TST_wchar = clang::TST_wchar;
243 static const TST TST_char16 = clang::TST_char16;
244 static const TST TST_char32 = clang::TST_char32;
245 static const TST TST_int = clang::TST_int;
246 static const TST TST_half = clang::TST_half;
247 static const TST TST_float = clang::TST_float;
248 static const TST TST_double = clang::TST_double;
249 static const TST TST_bool = clang::TST_bool;
250 static const TST TST_decimal32 = clang::TST_decimal32;
251 static const TST TST_decimal64 = clang::TST_decimal64;
252 static const TST TST_decimal128 = clang::TST_decimal128;
253 static const TST TST_enum = clang::TST_enum;
254 static const TST TST_union = clang::TST_union;
255 static const TST TST_struct = clang::TST_struct;
256 static const TST TST_class = clang::TST_class;
257 static const TST TST_typename = clang::TST_typename;
258 static const TST TST_typeofType = clang::TST_typeofType;
259 static const TST TST_typeofExpr = clang::TST_typeofExpr;
260 static const TST TST_decltype = clang::TST_decltype;
261 static const TST TST_underlyingType = clang::TST_underlyingType;
262 static const TST TST_auto = clang::TST_auto;
263 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
264 static const TST TST_atomic = clang::TST_atomic;
265 static const TST TST_error = clang::TST_error;
268 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
275 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
276 /// returned by getParsedSpecifiers.
277 enum ParsedSpecifiers {
279 PQ_StorageClassSpecifier = 1,
280 PQ_TypeSpecifier = 2,
281 PQ_TypeQualifier = 4,
282 PQ_FunctionSpecifier = 8
286 // storage-class-specifier
287 /*SCS*/unsigned StorageClassSpec : 3;
288 unsigned SCS_thread_specified : 1;
289 unsigned SCS_extern_in_linkage_spec : 1;
292 /*TSW*/unsigned TypeSpecWidth : 2;
293 /*TSC*/unsigned TypeSpecComplex : 2;
294 /*TSS*/unsigned TypeSpecSign : 2;
295 /*TST*/unsigned TypeSpecType : 5;
296 unsigned TypeAltiVecVector : 1;
297 unsigned TypeAltiVecPixel : 1;
298 unsigned TypeAltiVecBool : 1;
299 unsigned TypeSpecOwned : 1;
302 unsigned TypeQualifiers : 3; // Bitwise OR of TQ.
304 // function-specifier
305 unsigned FS_inline_specified : 1;
306 unsigned FS_virtual_specified : 1;
307 unsigned FS_explicit_specified : 1;
310 unsigned Friend_specified : 1;
312 // constexpr-specifier
313 unsigned Constexpr_specified : 1;
315 /*SCS*/unsigned StorageClassSpecAsWritten : 3;
318 UnionParsedType TypeRep;
324 ParsedAttributes Attrs;
326 // Scope specifier for the type spec, if applicable.
327 CXXScopeSpec TypeScope;
329 // List of protocol qualifiers for objective-c classes. Used for
330 // protocol-qualified interfaces "NString<foo>" and protocol-qualified id
332 Decl * const *ProtocolQualifiers;
333 unsigned NumProtocolQualifiers;
334 SourceLocation ProtocolLAngleLoc;
335 SourceLocation *ProtocolLocs;
337 // SourceLocation info. These are null if the item wasn't specified or if
338 // the setting was synthesized.
341 SourceLocation StorageClassSpecLoc, SCS_threadLoc;
342 SourceLocation TSWLoc, TSCLoc, TSSLoc, TSTLoc, AltiVecLoc;
343 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
344 /// typename, then this is the location of the named type (if present);
345 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
346 /// TSTNameLoc provides source range info for tag types.
347 SourceLocation TSTNameLoc;
348 SourceRange TypeofParensRange;
349 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc;
350 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc;
351 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
353 WrittenBuiltinSpecs writtenBS;
354 void SaveWrittenBuiltinSpecs();
355 void SaveStorageSpecifierAsWritten();
357 ObjCDeclSpec *ObjCQualifiers;
359 static bool isTypeRep(TST T) {
360 return (T == TST_typename || T == TST_typeofType ||
361 T == TST_underlyingType || T == TST_atomic);
363 static bool isExprRep(TST T) {
364 return (T == TST_typeofExpr || T == TST_decltype);
366 static bool isDeclRep(TST T) {
367 return (T == TST_enum || T == TST_struct ||
368 T == TST_union || T == TST_class);
371 DeclSpec(const DeclSpec&); // DO NOT IMPLEMENT
372 void operator=(const DeclSpec&); // DO NOT IMPLEMENT
375 DeclSpec(AttributeFactory &attrFactory)
376 : StorageClassSpec(SCS_unspecified),
377 SCS_thread_specified(false),
378 SCS_extern_in_linkage_spec(false),
379 TypeSpecWidth(TSW_unspecified),
380 TypeSpecComplex(TSC_unspecified),
381 TypeSpecSign(TSS_unspecified),
382 TypeSpecType(TST_unspecified),
383 TypeAltiVecVector(false),
384 TypeAltiVecPixel(false),
385 TypeAltiVecBool(false),
386 TypeSpecOwned(false),
387 TypeQualifiers(TQ_unspecified),
388 FS_inline_specified(false),
389 FS_virtual_specified(false),
390 FS_explicit_specified(false),
391 Friend_specified(false),
392 Constexpr_specified(false),
393 StorageClassSpecAsWritten(SCS_unspecified),
395 ProtocolQualifiers(0),
396 NumProtocolQualifiers(0),
402 delete [] ProtocolQualifiers;
403 delete [] ProtocolLocs;
405 // storage-class-specifier
406 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
407 bool isThreadSpecified() const { return SCS_thread_specified; }
408 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
409 void setExternInLinkageSpec(bool Value) {
410 SCS_extern_in_linkage_spec = Value;
413 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
414 SourceLocation getThreadSpecLoc() const { return SCS_threadLoc; }
416 void ClearStorageClassSpecs() {
417 StorageClassSpec = DeclSpec::SCS_unspecified;
418 SCS_thread_specified = false;
419 SCS_extern_in_linkage_spec = false;
420 StorageClassSpecLoc = SourceLocation();
421 SCS_threadLoc = SourceLocation();
425 TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
426 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
427 TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
428 TST getTypeSpecType() const { return (TST)TypeSpecType; }
429 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
430 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
431 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
432 bool isTypeSpecOwned() const { return TypeSpecOwned; }
433 ParsedType getRepAsType() const {
434 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
437 Decl *getRepAsDecl() const {
438 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
441 Expr *getRepAsExpr() const {
442 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
445 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
446 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
448 const SourceRange &getSourceRange() const { return Range; }
449 SourceLocation getTypeSpecWidthLoc() const { return TSWLoc; }
450 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
451 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
452 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
453 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
455 SourceLocation getTypeSpecTypeNameLoc() const {
456 assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename);
460 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
461 void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
463 /// getSpecifierName - Turn a type-specifier-type into a string like "_Bool"
465 static const char *getSpecifierName(DeclSpec::TST T);
466 static const char *getSpecifierName(DeclSpec::TQ Q);
467 static const char *getSpecifierName(DeclSpec::TSS S);
468 static const char *getSpecifierName(DeclSpec::TSC C);
469 static const char *getSpecifierName(DeclSpec::TSW W);
470 static const char *getSpecifierName(DeclSpec::SCS S);
474 /// getTypeQualifiers - Return a set of TQs.
475 unsigned getTypeQualifiers() const { return TypeQualifiers; }
476 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
477 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
478 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
480 /// \brief Clear out all of the type qualifiers.
481 void ClearTypeQualifiers() {
483 TQ_constLoc = SourceLocation();
484 TQ_restrictLoc = SourceLocation();
485 TQ_volatileLoc = SourceLocation();
488 // function-specifier
489 bool isInlineSpecified() const { return FS_inline_specified; }
490 SourceLocation getInlineSpecLoc() const { return FS_inlineLoc; }
492 bool isVirtualSpecified() const { return FS_virtual_specified; }
493 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
495 bool isExplicitSpecified() const { return FS_explicit_specified; }
496 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
498 void ClearFunctionSpecs() {
499 FS_inline_specified = false;
500 FS_inlineLoc = SourceLocation();
501 FS_virtual_specified = false;
502 FS_virtualLoc = SourceLocation();
503 FS_explicit_specified = false;
504 FS_explicitLoc = SourceLocation();
507 /// hasTypeSpecifier - Return true if any type-specifier has been found.
508 bool hasTypeSpecifier() const {
509 return getTypeSpecType() != DeclSpec::TST_unspecified ||
510 getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
511 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
512 getTypeSpecSign() != DeclSpec::TSS_unspecified;
515 /// getParsedSpecifiers - Return a bitmask of which flavors of specifiers this
516 /// DeclSpec includes.
518 unsigned getParsedSpecifiers() const;
520 SCS getStorageClassSpecAsWritten() const {
521 return (SCS)StorageClassSpecAsWritten;
524 /// isEmpty - Return true if this declaration specifier is completely empty:
525 /// no tokens were parsed in the production of it.
526 bool isEmpty() const {
527 return getParsedSpecifiers() == DeclSpec::PQ_None;
530 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
531 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
533 /// These methods set the specified attribute of the DeclSpec and
534 /// return false if there was no error. If an error occurs (for
535 /// example, if we tried to set "auto" on a spec with "extern"
536 /// already set), they return true and set PrevSpec and DiagID
538 /// Diag(Loc, DiagID) << PrevSpec;
539 /// will yield a useful result.
541 /// TODO: use a more general approach that still allows these
542 /// diagnostics to be ignored when desired.
543 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
544 const char *&PrevSpec, unsigned &DiagID);
545 bool SetStorageClassSpecThread(SourceLocation Loc, const char *&PrevSpec,
547 bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
549 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
551 bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
553 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
555 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
556 unsigned &DiagID, ParsedType Rep);
557 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
558 unsigned &DiagID, Decl *Rep, bool Owned);
559 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
560 SourceLocation TagNameLoc, const char *&PrevSpec,
561 unsigned &DiagID, ParsedType Rep);
562 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
563 SourceLocation TagNameLoc, const char *&PrevSpec,
564 unsigned &DiagID, Decl *Rep, bool Owned);
566 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
567 unsigned &DiagID, Expr *Rep);
568 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
569 const char *&PrevSpec, unsigned &DiagID);
570 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
571 const char *&PrevSpec, unsigned &DiagID);
572 bool SetTypeSpecError();
573 void UpdateDeclRep(Decl *Rep) {
574 assert(isDeclRep((TST) TypeSpecType));
577 void UpdateTypeRep(ParsedType Rep) {
578 assert(isTypeRep((TST) TypeSpecType));
581 void UpdateExprRep(Expr *Rep) {
582 assert(isExprRep((TST) TypeSpecType));
586 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
587 unsigned &DiagID, const LangOptions &Lang);
589 bool SetFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
591 bool SetFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
593 bool SetFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
596 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
598 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
600 bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
603 bool isFriendSpecified() const { return Friend_specified; }
604 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
606 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
607 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
609 bool isConstexprSpecified() const { return Constexpr_specified; }
610 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
612 AttributePool &getAttributePool() const {
613 return Attrs.getPool();
616 /// AddAttributes - contatenates two attribute lists.
617 /// The GCC attribute syntax allows for the following:
619 /// short __attribute__(( unused, deprecated ))
620 /// int __attribute__(( may_alias, aligned(16) )) var;
622 /// This declares 4 attributes using 2 lists. The following syntax is
623 /// also allowed and equivalent to the previous declaration.
625 /// short __attribute__((unused)) __attribute__((deprecated))
626 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
628 void addAttributes(AttributeList *AL) {
631 void setAttributes(AttributeList *AL) {
635 bool hasAttributes() const { return !Attrs.empty(); }
637 ParsedAttributes &getAttributes() { return Attrs; }
638 const ParsedAttributes &getAttributes() const { return Attrs; }
640 /// TakeAttributes - Return the current attribute list and remove them from
641 /// the DeclSpec so that it doesn't own them.
642 ParsedAttributes takeAttributes() {
643 // The non-const "copy" constructor clears the operand automatically.
647 void takeAttributesFrom(ParsedAttributes &attrs) {
648 Attrs.takeAllFrom(attrs);
651 typedef Decl * const *ProtocolQualifierListTy;
652 ProtocolQualifierListTy getProtocolQualifiers() const {
653 return ProtocolQualifiers;
655 SourceLocation *getProtocolLocs() const { return ProtocolLocs; }
656 unsigned getNumProtocolQualifiers() const {
657 return NumProtocolQualifiers;
659 SourceLocation getProtocolLAngleLoc() const { return ProtocolLAngleLoc; }
660 void setProtocolQualifiers(Decl * const *Protos, unsigned NP,
661 SourceLocation *ProtoLocs,
662 SourceLocation LAngleLoc);
664 /// Finish - This does final analysis of the declspec, issuing diagnostics for
665 /// things like "_Imaginary" (lacking an FP type). After calling this method,
666 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
667 void Finish(DiagnosticsEngine &D, Preprocessor &PP);
669 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
673 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
674 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
676 /// isMissingDeclaratorOk - This checks if this DeclSpec can stand alone,
677 /// without a Declarator. Only tag declspecs can stand alone.
678 bool isMissingDeclaratorOk();
681 /// ObjCDeclSpec - This class captures information about
682 /// "declaration specifiers" specific to objective-c
685 /// ObjCDeclQualifier - Qualifier used on types in method
686 /// declarations. Not all combinations are sensible. Parameters
687 /// can be one of { in, out, inout } with one of { bycopy, byref }.
688 /// Returns can either be { oneway } or not.
690 /// This should be kept in sync with Decl::ObjCDeclQualifier.
691 enum ObjCDeclQualifier {
701 /// PropertyAttributeKind - list of property attributes.
702 enum ObjCPropertyAttributeKind {
704 DQ_PR_readonly = 0x01,
707 DQ_PR_readwrite = 0x08,
710 DQ_PR_nonatomic = 0x40,
712 DQ_PR_atomic = 0x100,
714 DQ_PR_strong = 0x400,
715 DQ_PR_unsafe_unretained = 0x800
720 : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
721 GetterName(0), SetterName(0) { }
722 ObjCDeclQualifier getObjCDeclQualifier() const { return objcDeclQualifier; }
723 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
724 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
727 ObjCPropertyAttributeKind getPropertyAttributes() const {
728 return ObjCPropertyAttributeKind(PropertyAttributes);
730 void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
732 (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
735 const IdentifierInfo *getGetterName() const { return GetterName; }
736 IdentifierInfo *getGetterName() { return GetterName; }
737 void setGetterName(IdentifierInfo *name) { GetterName = name; }
739 const IdentifierInfo *getSetterName() const { return SetterName; }
740 IdentifierInfo *getSetterName() { return SetterName; }
741 void setSetterName(IdentifierInfo *name) { SetterName = name; }
744 // FIXME: These two are unrelated and mutially exclusive. So perhaps
745 // we can put them in a union to reflect their mutual exclusiveness
746 // (space saving is negligible).
747 ObjCDeclQualifier objcDeclQualifier : 6;
749 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
750 unsigned PropertyAttributes : 12;
751 IdentifierInfo *GetterName; // getter name of NULL if no getter
752 IdentifierInfo *SetterName; // setter name of NULL if no setter
755 /// \brief Represents a C++ unqualified-id that has been parsed.
756 class UnqualifiedId {
758 const UnqualifiedId &operator=(const UnqualifiedId &); // DO NOT IMPLEMENT
761 /// \brief Describes the kind of unqualified-id parsed.
763 /// \brief An identifier.
765 /// \brief An overloaded operator name, e.g., operator+.
766 IK_OperatorFunctionId,
767 /// \brief A conversion function name, e.g., operator int.
768 IK_ConversionFunctionId,
769 /// \brief A user-defined literal name, e.g., operator "" _i.
770 IK_LiteralOperatorId,
771 /// \brief A constructor name.
773 /// \brief A constructor named via a template-id.
774 IK_ConstructorTemplateId,
775 /// \brief A destructor name.
777 /// \brief A template-id, e.g., f<int>.
779 /// \brief An implicit 'self' parameter
783 /// \brief Anonymous union that holds extra data associated with the
784 /// parsed unqualified-id.
786 /// \brief When Kind == IK_Identifier, the parsed identifier, or when Kind
787 /// == IK_UserLiteralId, the identifier suffix.
788 IdentifierInfo *Identifier;
790 /// \brief When Kind == IK_OperatorFunctionId, the overloaded operator
793 /// \brief The kind of overloaded operator.
794 OverloadedOperatorKind Operator;
796 /// \brief The source locations of the individual tokens that name
797 /// the operator, e.g., the "new", "[", and "]" tokens in
800 /// Different operators have different numbers of tokens in their name,
801 /// up to three. Any remaining source locations in this array will be
802 /// set to an invalid value for operators with fewer than three tokens.
803 unsigned SymbolLocations[3];
804 } OperatorFunctionId;
806 /// \brief When Kind == IK_ConversionFunctionId, the type that the
807 /// conversion function names.
808 UnionParsedType ConversionFunctionId;
810 /// \brief When Kind == IK_ConstructorName, the class-name of the type
811 /// whose constructor is being referenced.
812 UnionParsedType ConstructorName;
814 /// \brief When Kind == IK_DestructorName, the type referred to by the
816 UnionParsedType DestructorName;
818 /// \brief When Kind == IK_TemplateId or IK_ConstructorTemplateId,
819 /// the template-id annotation that contains the template name and
820 /// template arguments.
821 TemplateIdAnnotation *TemplateId;
824 /// \brief The location of the first token that describes this unqualified-id,
825 /// which will be the location of the identifier, "operator" keyword,
826 /// tilde (for a destructor), or the template name of a template-id.
827 SourceLocation StartLocation;
829 /// \brief The location of the last token that describes this unqualified-id.
830 SourceLocation EndLocation;
832 UnqualifiedId() : Kind(IK_Identifier), Identifier(0) { }
834 /// \brief Do not use this copy constructor. It is temporary, and only
835 /// exists because we are holding FieldDeclarators in a SmallVector when we
836 /// don't actually need them.
838 /// FIXME: Kill this copy constructor.
839 UnqualifiedId(const UnqualifiedId &Other)
840 : Kind(IK_Identifier), Identifier(Other.Identifier),
841 StartLocation(Other.StartLocation), EndLocation(Other.EndLocation) {
842 assert(Other.Kind == IK_Identifier && "Cannot copy non-identifiers");
845 /// \brief Destroy this unqualified-id.
846 ~UnqualifiedId() { clear(); }
848 /// \brief Clear out this unqualified-id, setting it to default (invalid)
852 /// \brief Determine whether this unqualified-id refers to a valid name.
853 bool isValid() const { return StartLocation.isValid(); }
855 /// \brief Determine whether this unqualified-id refers to an invalid name.
856 bool isInvalid() const { return !isValid(); }
858 /// \brief Determine what kind of name we have.
859 IdKind getKind() const { return Kind; }
860 void setKind(IdKind kind) { Kind = kind; }
862 /// \brief Specify that this unqualified-id was parsed as an identifier.
864 /// \param Id the parsed identifier.
865 /// \param IdLoc the location of the parsed identifier.
866 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
867 Kind = IK_Identifier;
868 Identifier = const_cast<IdentifierInfo *>(Id);
869 StartLocation = EndLocation = IdLoc;
872 /// \brief Specify that this unqualified-id was parsed as an
873 /// operator-function-id.
875 /// \param OperatorLoc the location of the 'operator' keyword.
877 /// \param Op the overloaded operator.
879 /// \param SymbolLocations the locations of the individual operator symbols
881 void setOperatorFunctionId(SourceLocation OperatorLoc,
882 OverloadedOperatorKind Op,
883 SourceLocation SymbolLocations[3]);
885 /// \brief Specify that this unqualified-id was parsed as a
886 /// conversion-function-id.
888 /// \param OperatorLoc the location of the 'operator' keyword.
890 /// \param Ty the type to which this conversion function is converting.
892 /// \param EndLoc the location of the last token that makes up the type name.
893 void setConversionFunctionId(SourceLocation OperatorLoc,
895 SourceLocation EndLoc) {
896 Kind = IK_ConversionFunctionId;
897 StartLocation = OperatorLoc;
898 EndLocation = EndLoc;
899 ConversionFunctionId = Ty;
902 /// \brief Specific that this unqualified-id was parsed as a
903 /// literal-operator-id.
905 /// \param Id the parsed identifier.
907 /// \param OpLoc the location of the 'operator' keyword.
909 /// \param IdLoc the location of the identifier.
910 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
911 SourceLocation IdLoc) {
912 Kind = IK_LiteralOperatorId;
913 Identifier = const_cast<IdentifierInfo *>(Id);
914 StartLocation = OpLoc;
918 /// \brief Specify that this unqualified-id was parsed as a constructor name.
920 /// \param ClassType the class type referred to by the constructor name.
922 /// \param ClassNameLoc the location of the class name.
924 /// \param EndLoc the location of the last token that makes up the type name.
925 void setConstructorName(ParsedType ClassType,
926 SourceLocation ClassNameLoc,
927 SourceLocation EndLoc) {
928 Kind = IK_ConstructorName;
929 StartLocation = ClassNameLoc;
930 EndLocation = EndLoc;
931 ConstructorName = ClassType;
934 /// \brief Specify that this unqualified-id was parsed as a
935 /// template-id that names a constructor.
937 /// \param TemplateId the template-id annotation that describes the parsed
938 /// template-id. This UnqualifiedId instance will take ownership of the
939 /// \p TemplateId and will free it on destruction.
940 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
942 /// \brief Specify that this unqualified-id was parsed as a destructor name.
944 /// \param TildeLoc the location of the '~' that introduces the destructor
947 /// \param ClassType the name of the class referred to by the destructor name.
948 void setDestructorName(SourceLocation TildeLoc,
949 ParsedType ClassType,
950 SourceLocation EndLoc) {
951 Kind = IK_DestructorName;
952 StartLocation = TildeLoc;
953 EndLocation = EndLoc;
954 DestructorName = ClassType;
957 /// \brief Specify that this unqualified-id was parsed as a template-id.
959 /// \param TemplateId the template-id annotation that describes the parsed
960 /// template-id. This UnqualifiedId instance will take ownership of the
961 /// \p TemplateId and will free it on destruction.
962 void setTemplateId(TemplateIdAnnotation *TemplateId);
964 /// \brief Return the source range that covers this unqualified-id.
965 SourceRange getSourceRange() const {
966 return SourceRange(StartLocation, EndLocation);
970 /// CachedTokens - A set of tokens that has been cached for later
972 typedef SmallVector<Token, 4> CachedTokens;
974 /// DeclaratorChunk - One instance of this struct is used for each type in a
975 /// declarator that is parsed.
977 /// This is intended to be a small value object.
978 struct DeclaratorChunk {
980 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren
983 /// Loc - The place where this type was defined.
985 /// EndLoc - If valid, the place where this chunck ends.
986 SourceLocation EndLoc;
988 struct TypeInfoCommon {
989 AttributeList *AttrList;
992 struct PointerTypeInfo : TypeInfoCommon {
993 /// The type qualifiers: const/volatile/restrict.
994 unsigned TypeQuals : 3;
996 /// The location of the const-qualifier, if any.
997 unsigned ConstQualLoc;
999 /// The location of the volatile-qualifier, if any.
1000 unsigned VolatileQualLoc;
1002 /// The location of the restrict-qualifier, if any.
1003 unsigned RestrictQualLoc;
1009 struct ReferenceTypeInfo : TypeInfoCommon {
1010 /// The type qualifier: restrict. [GNU] C++ extension
1011 bool HasRestrict : 1;
1012 /// True if this is an lvalue reference, false if it's an rvalue reference.
1018 struct ArrayTypeInfo : TypeInfoCommon {
1019 /// The type qualifiers for the array: const/volatile/restrict.
1020 unsigned TypeQuals : 3;
1022 /// True if this dimension included the 'static' keyword.
1025 /// True if this dimension was [*]. In this case, NumElts is null.
1028 /// This is the size of the array, or null if [] or [*] was specified.
1029 /// Since the parser is multi-purpose, and we don't want to impose a root
1030 /// expression class on all clients, NumElts is untyped.
1036 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1037 /// declarator is parsed. There are two interesting styles of arguments here:
1038 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1039 /// lists will have information about the identifier, but no type information.
1040 /// Parameter type lists will have type info (if the actions module provides
1041 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1043 IdentifierInfo *Ident;
1044 SourceLocation IdentLoc;
1047 /// DefaultArgTokens - When the parameter's default argument
1048 /// cannot be parsed immediately (because it occurs within the
1049 /// declaration of a member function), it will be stored here as a
1050 /// sequence of tokens to be parsed once the class definition is
1051 /// complete. Non-NULL indicates that there is a default argument.
1052 CachedTokens *DefaultArgTokens;
1055 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1057 CachedTokens *DefArgTokens = 0)
1058 : Ident(ident), IdentLoc(iloc), Param(param),
1059 DefaultArgTokens(DefArgTokens) {}
1062 struct TypeAndRange {
1067 struct FunctionTypeInfo : TypeInfoCommon {
1068 /// hasPrototype - This is true if the function had at least one typed
1069 /// argument. If the function is () or (a,b,c), then it has no prototype,
1070 /// and is treated as a K&R-style function.
1071 unsigned hasPrototype : 1;
1073 /// isVariadic - If this function has a prototype, and if that
1074 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1075 /// contains the location of the ellipsis.
1076 unsigned isVariadic : 1;
1078 /// \brief Whether the ref-qualifier (if any) is an lvalue reference.
1079 /// Otherwise, it's an rvalue reference.
1080 unsigned RefQualifierIsLValueRef : 1;
1082 /// The type qualifiers: const/volatile/restrict.
1083 /// The qualifier bitmask values are the same as in QualType.
1084 unsigned TypeQuals : 3;
1086 /// ExceptionSpecType - An ExceptionSpecificationType value.
1087 unsigned ExceptionSpecType : 3;
1089 /// DeleteArgInfo - If this is true, we need to delete[] ArgInfo.
1090 unsigned DeleteArgInfo : 1;
1092 /// When isVariadic is true, the location of the ellipsis in the source.
1093 unsigned EllipsisLoc;
1095 /// NumArgs - This is the number of formal arguments provided for the
1099 /// NumExceptions - This is the number of types in the dynamic-exception-
1100 /// decl, if the function has one.
1101 unsigned NumExceptions;
1103 /// \brief The location of the ref-qualifier, if any.
1105 /// If this is an invalid location, there is no ref-qualifier.
1106 unsigned RefQualifierLoc;
1108 /// \brief The location of the 'mutable' qualifer in a lambda-declarator, if
1110 unsigned MutableLoc;
1112 /// \brief When ExceptionSpecType isn't EST_None or EST_Delayed, the
1113 /// location of the keyword introducing the spec.
1114 unsigned ExceptionSpecLoc;
1116 /// ArgInfo - This is a pointer to a new[]'d array of ParamInfo objects that
1117 /// describe the arguments for this function declarator. This is null if
1118 /// there are no arguments specified.
1122 /// \brief Pointer to a new[]'d array of TypeAndRange objects that
1123 /// contain the types in the function's dynamic exception specification
1124 /// and their locations, if there is one.
1125 TypeAndRange *Exceptions;
1127 /// \brief Pointer to the expression in the noexcept-specifier of this
1128 /// function, if it has one.
1132 /// TrailingReturnType - If this isn't null, it's the trailing return type
1133 /// specified. This is actually a ParsedType, but stored as void* to
1134 /// allow union storage.
1135 void *TrailingReturnType;
1137 /// freeArgs - reset the argument list to having zero arguments. This is
1138 /// used in various places for error recovery.
1140 if (DeleteArgInfo) {
1142 DeleteArgInfo = false;
1150 if (getExceptionSpecType() == EST_Dynamic)
1151 delete[] Exceptions;
1154 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1155 /// like "void foo(a,b,c)". In a function definition, this will be followed
1156 /// by the argument type definitions.
1157 bool isKNRPrototype() const {
1158 return !hasPrototype && NumArgs != 0;
1161 SourceLocation getEllipsisLoc() const {
1162 return SourceLocation::getFromRawEncoding(EllipsisLoc);
1164 SourceLocation getExceptionSpecLoc() const {
1165 return SourceLocation::getFromRawEncoding(ExceptionSpecLoc);
1168 /// \brief Retrieve the location of the ref-qualifier, if any.
1169 SourceLocation getRefQualifierLoc() const {
1170 return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1173 /// \brief Retrieve the location of the 'mutable' qualifier, if any.
1174 SourceLocation getMutableLoc() const {
1175 return SourceLocation::getFromRawEncoding(MutableLoc);
1178 /// \brief Determine whether this function declaration contains a
1180 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1182 /// \brief Determine whether this lambda-declarator contains a 'mutable'
1184 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1186 /// \brief Get the type of exception specification this function has.
1187 ExceptionSpecificationType getExceptionSpecType() const {
1188 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1192 struct BlockPointerTypeInfo : TypeInfoCommon {
1193 /// For now, sema will catch these as invalid.
1194 /// The type qualifiers: const/volatile/restrict.
1195 unsigned TypeQuals : 3;
1201 struct MemberPointerTypeInfo : TypeInfoCommon {
1202 /// The type qualifiers: const/volatile/restrict.
1203 unsigned TypeQuals : 3;
1204 // CXXScopeSpec has a constructor, so it can't be a direct member.
1205 // So we need some pointer-aligned storage and a bit of trickery.
1208 char Mem[sizeof(CXXScopeSpec)];
1210 CXXScopeSpec &Scope() {
1211 return *reinterpret_cast<CXXScopeSpec*>(ScopeMem.Mem);
1213 const CXXScopeSpec &Scope() const {
1214 return *reinterpret_cast<const CXXScopeSpec*>(ScopeMem.Mem);
1217 Scope().~CXXScopeSpec();
1222 TypeInfoCommon Common;
1223 PointerTypeInfo Ptr;
1224 ReferenceTypeInfo Ref;
1226 FunctionTypeInfo Fun;
1227 BlockPointerTypeInfo Cls;
1228 MemberPointerTypeInfo Mem;
1233 default: llvm_unreachable("Unknown decl type!");
1234 case DeclaratorChunk::Function: return Fun.destroy();
1235 case DeclaratorChunk::Pointer: return Ptr.destroy();
1236 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1237 case DeclaratorChunk::Reference: return Ref.destroy();
1238 case DeclaratorChunk::Array: return Arr.destroy();
1239 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1240 case DeclaratorChunk::Paren: return;
1244 /// getAttrs - If there are attributes applied to this declaratorchunk, return
1246 const AttributeList *getAttrs() const {
1247 return Common.AttrList;
1250 AttributeList *&getAttrListRef() {
1251 return Common.AttrList;
1254 /// getPointer - Return a DeclaratorChunk for a pointer.
1256 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1257 SourceLocation ConstQualLoc,
1258 SourceLocation VolatileQualLoc,
1259 SourceLocation RestrictQualLoc) {
1263 I.Ptr.TypeQuals = TypeQuals;
1264 I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding();
1265 I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1266 I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1271 /// getReference - Return a DeclaratorChunk for a reference.
1273 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1278 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1279 I.Ref.LValueRef = lvalue;
1284 /// getArray - Return a DeclaratorChunk for an array.
1286 static DeclaratorChunk getArray(unsigned TypeQuals,
1287 bool isStatic, bool isStar, Expr *NumElts,
1288 SourceLocation LBLoc, SourceLocation RBLoc) {
1294 I.Arr.TypeQuals = TypeQuals;
1295 I.Arr.hasStatic = isStatic;
1296 I.Arr.isStar = isStar;
1297 I.Arr.NumElts = NumElts;
1301 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1302 /// "TheDeclarator" is the declarator that this will be added to.
1303 static DeclaratorChunk getFunction(bool hasProto, bool isVariadic,
1304 SourceLocation EllipsisLoc,
1305 ParamInfo *ArgInfo, unsigned NumArgs,
1307 bool RefQualifierIsLvalueRef,
1308 SourceLocation RefQualifierLoc,
1309 SourceLocation MutableLoc,
1310 ExceptionSpecificationType ESpecType,
1311 SourceLocation ESpecLoc,
1312 ParsedType *Exceptions,
1313 SourceRange *ExceptionRanges,
1314 unsigned NumExceptions,
1316 SourceLocation LocalRangeBegin,
1317 SourceLocation LocalRangeEnd,
1318 Declarator &TheDeclarator,
1319 ParsedType TrailingReturnType =
1322 /// getBlockPointer - Return a DeclaratorChunk for a block.
1324 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1325 SourceLocation Loc) {
1327 I.Kind = BlockPointer;
1329 I.Cls.TypeQuals = TypeQuals;
1334 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1336 SourceLocation Loc) {
1338 I.Kind = MemberPointer;
1340 I.Mem.TypeQuals = TypeQuals;
1342 new (I.Mem.ScopeMem.Mem) CXXScopeSpec(SS);
1346 /// getParen - Return a DeclaratorChunk for a paren.
1348 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1349 SourceLocation RParenLoc) {
1353 I.EndLoc = RParenLoc;
1354 I.Common.AttrList = 0;
1360 /// Declarator - Information about one declarator, including the parsed type
1361 /// information and the identifier. When the declarator is fully formed, this
1362 /// is turned into the appropriate Decl object.
1364 /// Declarators come in two types: normal declarators and abstract declarators.
1365 /// Abstract declarators are used when parsing types, and don't have an
1366 /// identifier. Normal declarators do have ID's.
1368 /// Instances of this class should be a transient object that lives on the
1369 /// stack, not objects that are allocated in large quantities on the heap.
1373 FileContext, // File scope declaration.
1374 PrototypeContext, // Within a function prototype.
1375 ObjCResultContext, // An ObjC method result type.
1376 ObjCParameterContext,// An ObjC method parameter type.
1377 KNRTypeListContext, // K&R type definition list for formals.
1378 TypeNameContext, // Abstract declarator for types.
1379 MemberContext, // Struct/Union field.
1380 BlockContext, // Declaration within a block in a function.
1381 ForContext, // Declaration within first part of a for loop.
1382 ConditionContext, // Condition declaration in a C++ if/switch/while/for.
1383 TemplateParamContext,// Within a template parameter list.
1384 CXXNewContext, // C++ new-expression.
1385 CXXCatchContext, // C++ catch exception-declaration
1386 ObjCCatchContext, // Objective-C catch exception-declaration
1387 BlockLiteralContext, // Block literal declarator.
1388 TemplateTypeArgContext, // Template type argument.
1389 AliasDeclContext, // C++0x alias-declaration.
1390 AliasTemplateContext // C++0x alias-declaration template.
1399 /// Context - Where we are parsing this declarator.
1403 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1404 /// parsed. This is pushed from the identifier out, which means that element
1405 /// #0 will be the most closely bound to the identifier, and
1406 /// DeclTypeInfo.back() will be the least closely bound.
1407 SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1409 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1410 bool InvalidType : 1;
1412 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1413 bool GroupingParens : 1;
1415 /// FunctionDefinition - Is this Declarator for a function or member defintion
1416 bool FunctionDefinition : 1;
1418 // Redeclaration - Is this Declarator is a redeclaration.
1419 bool Redeclaration : 1;
1421 /// Attrs - Attributes.
1422 ParsedAttributes Attrs;
1424 /// AsmLabel - The asm label, if specified.
1427 /// InlineParams - This is a local array used for the first function decl
1428 /// chunk to avoid going to the heap for the common case when we have one
1429 /// function chunk in the declarator.
1430 DeclaratorChunk::ParamInfo InlineParams[16];
1431 bool InlineParamsUsed;
1433 /// Extension - true if the declaration is preceded by __extension__.
1436 /// \brief If provided, the source location of the ellipsis used to describe
1437 /// this declarator as a parameter pack.
1438 SourceLocation EllipsisLoc;
1440 friend struct DeclaratorChunk;
1443 Declarator(const DeclSpec &ds, TheContext C)
1444 : DS(ds), Range(ds.getSourceRange()), Context(C),
1445 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1446 GroupingParens(false), FunctionDefinition(false), Redeclaration(false),
1447 Attrs(ds.getAttributePool().getFactory()), AsmLabel(0),
1448 InlineParamsUsed(false), Extension(false) {
1455 /// getDeclSpec - Return the declaration-specifier that this declarator was
1457 const DeclSpec &getDeclSpec() const { return DS; }
1459 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1460 /// should be used with extreme care: declspecs can often be shared between
1461 /// multiple declarators, so mutating the DeclSpec affects all of the
1462 /// Declarators. This should only be done when the declspec is known to not
1463 /// be shared or when in error recovery etc.
1464 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1466 AttributePool &getAttributePool() const {
1467 return Attrs.getPool();
1470 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1471 /// nested-name-specifier) that is part of the declarator-id.
1472 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1473 CXXScopeSpec &getCXXScopeSpec() { return SS; }
1475 /// \brief Retrieve the name specified by this declarator.
1476 UnqualifiedId &getName() { return Name; }
1478 TheContext getContext() const { return Context; }
1480 bool isPrototypeContext() const {
1481 return (Context == PrototypeContext ||
1482 Context == ObjCParameterContext ||
1483 Context == ObjCResultContext);
1486 /// getSourceRange - Get the source range that spans this declarator.
1487 const SourceRange &getSourceRange() const { return Range; }
1489 void SetSourceRange(SourceRange R) { Range = R; }
1490 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1492 void SetRangeBegin(SourceLocation Loc) {
1493 if (!Loc.isInvalid())
1494 Range.setBegin(Loc);
1496 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1497 void SetRangeEnd(SourceLocation Loc) {
1498 if (!Loc.isInvalid())
1501 /// ExtendWithDeclSpec - Extend the declarator source range to include the
1502 /// given declspec, unless its location is invalid. Adopts the range start if
1503 /// the current range start is invalid.
1504 void ExtendWithDeclSpec(const DeclSpec &DS) {
1505 const SourceRange &SR = DS.getSourceRange();
1506 if (Range.getBegin().isInvalid())
1507 Range.setBegin(SR.getBegin());
1508 if (!SR.getEnd().isInvalid())
1509 Range.setEnd(SR.getEnd());
1512 /// clear - Reset the contents of this Declarator.
1516 Range = DS.getSourceRange();
1518 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1519 DeclTypeInfo[i].destroy();
1520 DeclTypeInfo.clear();
1523 InlineParamsUsed = false;
1526 /// mayOmitIdentifier - Return true if the identifier is either optional or
1527 /// not allowed. This is true for typenames, prototypes, and template
1528 /// parameter lists.
1529 bool mayOmitIdentifier() const {
1532 case KNRTypeListContext:
1536 case ConditionContext:
1539 case TypeNameContext:
1540 case AliasDeclContext:
1541 case AliasTemplateContext:
1542 case PrototypeContext:
1543 case ObjCParameterContext:
1544 case ObjCResultContext:
1545 case TemplateParamContext:
1547 case CXXCatchContext:
1548 case ObjCCatchContext:
1549 case BlockLiteralContext:
1550 case TemplateTypeArgContext:
1553 llvm_unreachable("unknown context kind!");
1556 /// mayHaveIdentifier - Return true if the identifier is either optional or
1557 /// required. This is true for normal declarators and prototypes, but not
1559 bool mayHaveIdentifier() const {
1562 case KNRTypeListContext:
1566 case ConditionContext:
1567 case PrototypeContext:
1568 case TemplateParamContext:
1569 case CXXCatchContext:
1570 case ObjCCatchContext:
1573 case TypeNameContext:
1575 case AliasDeclContext:
1576 case AliasTemplateContext:
1577 case ObjCParameterContext:
1578 case ObjCResultContext:
1579 case BlockLiteralContext:
1580 case TemplateTypeArgContext:
1583 llvm_unreachable("unknown context kind!");
1586 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
1587 /// followed by a C++ direct initializer, e.g. "int x(1);".
1588 bool mayBeFollowedByCXXDirectInit() const {
1589 if (hasGroupingParens()) return false;
1597 case KNRTypeListContext:
1599 case ConditionContext:
1600 case PrototypeContext:
1601 case ObjCParameterContext:
1602 case ObjCResultContext:
1603 case TemplateParamContext:
1604 case CXXCatchContext:
1605 case ObjCCatchContext:
1606 case TypeNameContext:
1608 case AliasDeclContext:
1609 case AliasTemplateContext:
1610 case BlockLiteralContext:
1611 case TemplateTypeArgContext:
1614 llvm_unreachable("unknown context kind!");
1617 /// isPastIdentifier - Return true if we have parsed beyond the point where
1619 bool isPastIdentifier() const { return Name.isValid(); }
1621 /// hasName - Whether this declarator has a name, which might be an
1622 /// identifier (accessible via getIdentifier()) or some kind of
1623 /// special C++ name (constructor, destructor, etc.).
1624 bool hasName() const {
1625 return Name.getKind() != UnqualifiedId::IK_Identifier || Name.Identifier;
1628 IdentifierInfo *getIdentifier() const {
1629 if (Name.getKind() == UnqualifiedId::IK_Identifier)
1630 return Name.Identifier;
1634 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
1636 /// \brief Set the name of this declarator to be the given identifier.
1637 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
1638 Name.setIdentifier(Id, IdLoc);
1641 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
1642 /// EndLoc, which should be the last token of the chunk.
1643 void AddTypeInfo(const DeclaratorChunk &TI,
1644 ParsedAttributes &attrs,
1645 SourceLocation EndLoc) {
1646 DeclTypeInfo.push_back(TI);
1647 DeclTypeInfo.back().getAttrListRef() = attrs.getList();
1648 getAttributePool().takeAllFrom(attrs.getPool());
1650 if (!EndLoc.isInvalid())
1651 SetRangeEnd(EndLoc);
1654 /// AddInnermostTypeInfo - Add a new innermost chunk to this declarator.
1655 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
1656 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
1659 /// getNumTypeObjects() - Return the number of types applied to this
1661 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
1663 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
1664 /// closest to the identifier.
1665 const DeclaratorChunk &getTypeObject(unsigned i) const {
1666 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1667 return DeclTypeInfo[i];
1669 DeclaratorChunk &getTypeObject(unsigned i) {
1670 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1671 return DeclTypeInfo[i];
1674 void DropFirstTypeObject()
1676 assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
1677 DeclTypeInfo.front().destroy();
1678 DeclTypeInfo.erase(DeclTypeInfo.begin());
1681 /// isArrayOfUnknownBound - This method returns true if the declarator
1682 /// is a declarator for an array of unknown bound (looking through
1684 bool isArrayOfUnknownBound() const {
1685 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1686 switch (DeclTypeInfo[i].Kind) {
1687 case DeclaratorChunk::Paren:
1689 case DeclaratorChunk::Function:
1690 case DeclaratorChunk::Pointer:
1691 case DeclaratorChunk::Reference:
1692 case DeclaratorChunk::BlockPointer:
1693 case DeclaratorChunk::MemberPointer:
1695 case DeclaratorChunk::Array:
1696 return !DeclTypeInfo[i].Arr.NumElts;
1698 llvm_unreachable("Invalid type chunk");
1704 /// isFunctionDeclarator - This method returns true if the declarator
1705 /// is a function declarator (looking through parentheses).
1706 /// If true is returned, then the reference type parameter idx is
1707 /// assigned with the index of the declaration chunk.
1708 bool isFunctionDeclarator(unsigned& idx) const {
1709 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1710 switch (DeclTypeInfo[i].Kind) {
1711 case DeclaratorChunk::Function:
1714 case DeclaratorChunk::Paren:
1716 case DeclaratorChunk::Pointer:
1717 case DeclaratorChunk::Reference:
1718 case DeclaratorChunk::Array:
1719 case DeclaratorChunk::BlockPointer:
1720 case DeclaratorChunk::MemberPointer:
1723 llvm_unreachable("Invalid type chunk");
1729 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
1730 /// this method returns true if the identifier is a function declarator
1731 /// (looking through parentheses).
1732 bool isFunctionDeclarator() const {
1734 return isFunctionDeclarator(index);
1737 /// getFunctionTypeInfo - Retrieves the function type info object
1738 /// (looking through parentheses).
1739 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
1740 assert(isFunctionDeclarator() && "Not a function declarator!");
1742 isFunctionDeclarator(index);
1743 return DeclTypeInfo[index].Fun;
1746 /// getFunctionTypeInfo - Retrieves the function type info object
1747 /// (looking through parentheses).
1748 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
1749 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
1752 /// \brief Determine whether the declaration that will be produced from
1753 /// this declaration will be a function.
1755 /// A declaration can declare a function even if the declarator itself
1756 /// isn't a function declarator, if the type specifier refers to a function
1757 /// type. This routine checks for both cases.
1758 bool isDeclarationOfFunction() const;
1760 /// takeAttributes - Takes attributes from the given parsed-attributes
1761 /// set and add them to this declarator.
1763 /// These examples both add 3 attributes to "var":
1764 /// short int var __attribute__((aligned(16),common,deprecated));
1765 /// short int x, __attribute__((aligned(16)) var
1766 /// __attribute__((common,deprecated));
1768 /// Also extends the range of the declarator.
1769 void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
1770 Attrs.takeAllFrom(attrs);
1772 if (!lastLoc.isInvalid())
1773 SetRangeEnd(lastLoc);
1776 const AttributeList *getAttributes() const { return Attrs.getList(); }
1777 AttributeList *getAttributes() { return Attrs.getList(); }
1779 AttributeList *&getAttrListRef() { return Attrs.getListRef(); }
1781 /// hasAttributes - do we contain any attributes?
1782 bool hasAttributes() const {
1783 if (getAttributes() || getDeclSpec().hasAttributes()) return true;
1784 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
1785 if (getTypeObject(i).getAttrs())
1790 void setAsmLabel(Expr *E) { AsmLabel = E; }
1791 Expr *getAsmLabel() const { return AsmLabel; }
1793 void setExtension(bool Val = true) { Extension = Val; }
1794 bool getExtension() const { return Extension; }
1796 void setInvalidType(bool Val = true) { InvalidType = Val; }
1797 bool isInvalidType() const {
1798 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
1801 void setGroupingParens(bool flag) { GroupingParens = flag; }
1802 bool hasGroupingParens() const { return GroupingParens; }
1804 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
1805 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
1806 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
1808 void setFunctionDefinition(bool Val) { FunctionDefinition = Val; }
1809 bool isFunctionDefinition() const { return FunctionDefinition; }
1811 void setRedeclaration(bool Val) { Redeclaration = Val; }
1812 bool isRedeclaration() const { return Redeclaration; }
1815 /// FieldDeclarator - This little struct is used to capture information about
1816 /// structure field declarators, which is basically just a bitfield size.
1817 struct FieldDeclarator {
1820 explicit FieldDeclarator(DeclSpec &DS) : D(DS, Declarator::MemberContext) {
1825 /// VirtSpecifiers - Represents a C++0x virt-specifier-seq.
1826 class VirtSpecifiers {
1834 VirtSpecifiers() : Specifiers(0) { }
1836 bool SetSpecifier(Specifier VS, SourceLocation Loc,
1837 const char *&PrevSpec);
1839 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
1840 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
1842 bool isFinalSpecified() const { return Specifiers & VS_Final; }
1843 SourceLocation getFinalLoc() const { return VS_finalLoc; }
1845 void clear() { Specifiers = 0; }
1847 static const char *getSpecifierName(Specifier VS);
1849 SourceLocation getLastLocation() const { return LastLocation; }
1852 unsigned Specifiers;
1854 SourceLocation VS_overrideLoc, VS_finalLoc;
1855 SourceLocation LastLocation;
1858 /// LambdaCaptureDefault - The default, if any, capture method for a
1859 /// lambda expression.
1860 enum LambdaCaptureDefault {
1866 /// LambdaCaptureKind - The different capture forms in a lambda
1867 /// introducer: 'this' or a copied or referenced variable.
1868 enum LambdaCaptureKind {
1874 /// LambdaCapture - An individual capture in a lambda introducer.
1875 struct LambdaCapture {
1876 LambdaCaptureKind Kind;
1880 LambdaCapture(LambdaCaptureKind Kind,
1882 IdentifierInfo* Id = 0)
1883 : Kind(Kind), Loc(Loc), Id(Id)
1887 /// LambdaIntroducer - Represents a complete lambda introducer.
1888 struct LambdaIntroducer {
1890 LambdaCaptureDefault Default;
1891 llvm::SmallVector<LambdaCapture, 4> Captures;
1894 : Default(LCD_None) {}
1896 /// addCapture - Append a capture in a lambda introducer.
1897 void addCapture(LambdaCaptureKind Kind,
1899 IdentifierInfo* Id = 0) {
1900 Captures.push_back(LambdaCapture(Kind, Loc, Id));
1905 } // end namespace clang